Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding element in two dimensional ArrayList

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?

like image 722
FranXh Avatar asked Mar 03 '12 23:03

FranXh


People also ask

Can ArrayLists be 2D?

Arrays can be created in 1D or 2D. 1D arrays are just one row of values, while 2D arrays contain a grid of values that has several rows/columns. 1D: 2D: An ArrayList is just like a 1D Array except it's length is unbounded and you can add as many elements as you need.

How do you add two-dimensional arrays?

Syntax: data_type[1st dimension][2nd dimension][]..[Nth dimension] array_name = new data_type[size1][size2]….[sizeN];

Can we create 2D array using ArrayList in Java?

Example of 2D ArrayList in Java The example explains the process of creating a 2-dimensional array list and then adding a value to the array list and then the value is attempted to be replaced with a different value. The first key process is to declare the headers for creating the two dimensional array list.


1 Answers

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.

like image 179
Joey Avatar answered Sep 18 '22 15:09

Joey