Adding element in two dimensional ArrayList

81,996

Solution 1

myList.get(0).set(1, 17);

maybe?

This assumes a nested ArrayList, i.e.

ArrayList<ArrayList<Integer>> myList;

And to pick on your choice of words: This assigns a value to a specific place in the inner list, it doesn't add one. But so does your code example, as arrays are of a fixed size, so you have to create them in the right size and then assign values to the individual element slots.

If you actually want to add an element, then of course it's .add(17), but that's not what your code did, so I went with the code above.

Solution 2

outerList.get(0).set(1, 17);

with outerList being a List<List<Integer>>.

Remember that 2-dimensional arrays don't exist. They're in fact arrays or arrays.

Solution 3

 ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
 data.add(new ArrayList<String>());
 data.get(0).add("String");

ArrayList<ArrayList<String>> contains elements of type ArrayList<String>

Each element must be initialised

These elements contain elements of type String

To get back the String "String" in the 3-line example, you would use

String getValue = data.get(0).get(0);

Solution 4

ArrayList<ArrayList<Integer>> FLCP = new ArrayList<ArrayList<Integer>>();
FLCP.add(new ArrayList<Integer>());
FLCP.get(0).add(new Integer(0));

Each element must be instantiated. Here the outer ArrayList has ArrayList element, and first you need to add an element to reference it using get method.

Some additional notes; after reading other answers and comments:

1> Each element must be instantiated; initialization is different from instantiation (refer to flexJavaMysql's answer)

2> In Java, 2-dimensional arrays do exist; C# doesn't have 2D arrays (refer to JB Nizet's answer)

Share:
81,996
FranXh
Author by

FranXh

Updated on July 09, 2022

Comments

  • FranXh
    FranXh almost 2 years

    I know that for arrays you can add an element in a two dimensional array this way:

     array[0][1] = 17; //just an example
    

    How can I do the same thing with ArrayList?

  • Oliver Charlesworth
    Oliver Charlesworth about 12 years
    I'm so glad James Gosling scorned operator overloads.
  • DNA
    DNA about 12 years
    ...where get(0) returns a List, of course. Also noting that 17 is autoboxed to new Integer(17)