Two-dimensional array of Lists
Solution 1
Fix the first method as following:
List[][] foo = new ArrayList[4][4];
The second method is not what you need. You are trying to create 4 dimensional array instead of 2 dimensional array 4*4 elements.
Additionally I'd like to give you a tip: never use concrete class in the left of assignment, i.e. ArrayList list = ....
Use List list = ...
And avoid using too complicated data structures. 2 dimensional array of lists is too complicated. Create your custom class that encapsulates some functionality and then create collection / array (better 1 dimensional) of objects of your class.
Solution 2
Here's example for 2x2 matrix with explicit initialization.
List<MyClass>[][] matr = new List<MyClass>[][] { new List<MyClass> { new ArrayList<MyClass>(), new ArrayList<MyClass>() }, new List<MyClass> { new ArrayList<MyClass>(), new ArrayList<MyClass>() } }
Mattias
Updated on July 19, 2020Comments
-
Mattias almost 4 years
I'm in the need of a two dimensional matrix of list, e.g. ArrayList, and I'm wondering what is most preferable in this case. It only needs to be 4x4 in size.
Should I use something like
ArrayList[][] foo = new ArrayList[4][4];
or
ArrayList<SomeClass>[][] foo = new ArrayList[4][4];
and initialize every element with the proper type in a for loop or
ArrayList<ArrayList<ArrayList<SomeClass>>> foo = ArrayList<ArrayList<ArrayList<SomeClass>>>();
The first method generates warnings like it should be parametrized and if I add use the second I get unchecked conversion warnings. But if I loop over the elements and initialize them there should not be any problem even if I still get the warning? The last method does not generate any warnings and probably works fine but it feels kinda messy.
EDIT: Got some nice answers to my question even if it was a bit unclear. But it was basically how to make a table of Lists. Creating a custom class to handle rows/columns it made it a a lot easier.
-
Mattias almost 13 yearsOkey, thank you for the tip! Could you please explain why you never want to use a concrete class in the left of assignment? With the custom class, I'd still want something that resembles a 2D array. But instead implement it as a 1D array and create some methods like
getRow()
andgetColumn()
? -
Thomas almost 13 years@Mattias In most cases you'd like to use the interface instead of a concrete class, since then you could exchange the
ArrayList
with aLinkedList
if needed. If you need more information on the capabilities (like sorted or not) you might have additional interfaces (considerSet
vs.SortedSet
) but knowing the concrete implementations is rarely useful to the user of a method. -
Mattias almost 13 years@AlexR Ah, I see. Thank you for the explanation! I think I have sorted it out now, made a custom class defining each column and a method to insert the result into the correct position. It made everything a lot easier.
-
Ace McCloud about 3 yearsHi is it possible to make it with generics ?