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?
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.
Syntax: data_type[1st dimension][2nd dimension][]..[Nth dimension] array_name = new data_type[size1][size2]….[sizeN];
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With