-5

How can I add a list to an empty list of lists?

Like:

static int[][] Pos = new int[][2]; //this actually don't work
// list1 = [0, 1]; list2 = [2, 3]
Pos.add(list1); 
Pos.add(list2);

"Pos" should return this:

[[0, 1], [2, 3]]

How is this possible?

9
  • 6
    You don't have a List of List. Commented May 2, 2014 at 19:24
  • 1
    You need to work on your syntax too... [0, 1] isn't valid Java. Commented May 2, 2014 at 19:24
  • 4
    Yo dawg, I heard you like lists... Commented May 2, 2014 at 19:26
  • 2
    @ElGavilan So I put a list into your list of lists, so you can add to list while adding to list Commented May 2, 2014 at 19:27
  • 1
    @user3580294 No actually you can leave the second empty. int[][] a = new int[2][]; is valid. Commented May 2, 2014 at 19:28

2 Answers 2

4

From your current code, you want to initialize an array of arrays of ints.

static int[][] Pos = new int[2][];

static {
    int[] array1 = { 0, 1 };
    int array2 = { 2, 3 };
    Pos[0] = array1; 
    Pos[1] = array2;
}

More info:


In case you want/need real Lists, you may use one of these approaches:

You're looking for a List<Integer[]>:

static List<Integer[]> Pos = new ArrayList<Integer[]>();

static {
    Pos.add(new Integer[] { 0, 1 } );
    Pos.add(new Integer[] { 2, 3 } );
}

Or a better option: List<List<Integer>>:

static List<List<Integer>> Pos = new ArrayList<List<Integer>>();

static {
    List<Integer> list = new ArrayList<Integer>();
    list.add(0);
    list.add(1);
    Pos.add(list);
    list = new ArrayList<Integer>();
    list.add(2);
    list.add(3);
    Pos.add(list);
}
Sign up to request clarification or add additional context in comments.

1 Comment

probably some glitch or you fixed that already. Never mind.
2

Declare a list of lists.

ArrayList<ArrayList<Integer>> pos = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
pos.add(list1);    
pos.add(list2);

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.