BlackJack BlackJack - 5 months ago 14
Java Question

Insert int Array to ArrayList

Can I insert array to array and read it afterwards in Java? Something like this:

ArrayList<Integer> array = new ArrayList<>();
array.add([1,4,5]);
array.add([3,7,2]);


Array:

{ [1,4,5], [3,7,2] }


And read like:

print(array[0][1]); //prints 4


Thanks.

Answer

You could write ArrayList<int[]> and pass values like .add(new int[]{...}).

For example,

List<int[]> list = new ArrayList<>();
list.add(new int[]{1, 2, 3});

To print values out you should get int[] firstly by get(int index) and by [] get a value from the array:

System.out.print(list.get(0)[0]); // 1