Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 318
blackJack Avatar asked Oct 25 '25 01:10

blackJack


1 Answers

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 an int[] array firstly by get(int index) and then get a value from this array by [index]:

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

About the mess in the comments.

  1. There are no raw types here. I didn't write, for example, List or List<Object> anywhere.
  2. int[] is an array, therefore it is a reference type and can be used as a generic parameter.
  3. int is a primitive which doesn't work/use with generics. Consider its wrapper class - Integer.
  4. I used the diamond <> above. Why? To prevent "boilerplate code".

In Java SE 7 and later, you can replace the type arguments required to invoke the constructor of a generic class with an empty set of type arguments (<>) as long as the compiler can determine, or infer, the type arguments from the context. This pair of angle brackets, <>, is informally called the diamond.
List<int[]> list = new ArrayList<>();
List<int[]> list = new ArrayList<int[]>(); is equivalent to the previous

like image 63
Andrew Tobilko Avatar answered Oct 27 '25 13:10

Andrew Tobilko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!