Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two-dimensional array of Lists

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.

like image 745
Mattias Avatar asked Jul 15 '26 04:07

Mattias


1 Answers

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.

like image 54
AlexR Avatar answered Jul 19 '26 19:07

AlexR