0

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

4
  • 1
    When asking a question please provide a reproducibl example, here missing the User class Commented May 14, 2022 at 12:04
  • 1
    Where is arrayList defined ? Commented May 14, 2022 at 12:05
  • 1
    In each box a the 2D array : there is a 1D or a 2D list ? Because what you write ends up in a 4-dimension structure Commented May 14, 2022 at 12:07
  • arrayList[0][0].add(list); Your "arrayList" which is actually an array doesn't have methods. You just assign a reference. arrayList[0][0] = list; Commented May 14, 2022 at 12:12

1 Answer 1

1

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

}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.