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>();
User user = new User(1,3,2,6);

enter image description here

>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 );


Leave a Reply