简体   繁体   中英

2D array of ArrayLists vs 3D ArrayList in Java

I need to store a list of unknown number of objects in a 2D array of fixed length. Example I have a 2d array:

int[][] clashesMatrix = new int[noOfExams][noOfExams];

and in each clashesMatrix position I need an arraylist of dynamic size with a Student object. I tried to do this:

ArrayList<Student>[][] clashesMatrix2 = new ArrayList<Student>[][];

but this gives a syntax error: Cannot create a generic array of ArrayList<Student> . Is there a way in which I can accomplish my goal with this?

There is another option of course to have a 3 Dimensional ArrayList

ArrayList<ArrayList<ArrayList<Student>>> clashesMatrix = new ArrayList<ArrayList<ArrayList<Student>>>();

What would you suggest to use for this purpose? And if I use the 2nd option of 3D arraylists what is the best way to initialize all the arraylist since of course everything would be null in the beginning? Would this be an overhead to loop over and initialize all arraylists I need?

You could try this but you'll get a compiler warning

ArrayList<Student>[][] clashesMatrix2 = (ArrayList<Student>[][]) java.lang.reflect.Array.newInstance(ArrayList.class,noOfExams,noOfExams);

You could do this to suppress warning

@SuppressWarnings("unchecked")
ArrayList<Student>[][] clashesMatrix2 = (ArrayList<Student>[][]) java.lang.reflect.Array.newInstance(ArrayList.class,noOfExams,noOfExams);

More info about this can be found at http://www.ibm.com/developerworks/java/library/j-jtp01255/index.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM