Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I create a two dimensional array with each element being a list in Java?

I want to create a two-dimensional array, each element of which is a list, as in the image.
I tried ArrayList<List<User>>[][] arrayList = new ArrayList[3][3];

Is this a correct solution? Because when I try to add element like below code I get null error.

List<User> list = new ArrayList<User>();
arrayList[0][0].add(list);
User user = new User(1,3,2,6);
arrayList[0][0].get(0).add(user);
System.out.println(arrayList[0][0].get(0).get(0).id);

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This compiles and runs for me. Note I changed your definition of "arrayList" to match your diagram better. I think this is what you want. However it’s simple to extend if you need something different.

public class ArrayOfList {

   public static void main( String[] args ) {
      ArrayList<User>[][] arrayOfLists = new ArrayList[ 3 ][ 3 ];
      arrayOfLists = new ArrayList[ 3 ][ 3 ];
      ArrayList<User> list = new ArrayList<User>();
      arrayOfLists[0][0] = list;
      User user = new User( 1, 3, 2, 6 );
      arrayOfLists[0][0].add( user );
      System.out.println( arrayOfLists[0][0].get( 0 ).id );
   }

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading