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.
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.
List or List<Object> anywhere.int[] is an array, therefore it is a reference type and can be used as a generic parameter.int is a primitive which doesn't work/use with generics. Consider its wrapper class - Integer.<> 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
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