I'm new to the concept of arraylist. I've made a short program that is as follows:
ArrayList<int[]> arl=new ArrayList<int[]>(); int a1[]={1,2,3}; arl.add(0,a1); System.out.println("Arraylist contains:"+arl.get(0));
It gives the output: Arraylist contains:[I@3e25a5
Now my questions are:
First of all, for initializing a container you cannot use a primitive type (i.e. int
; you can use int[]
but as you want just an array of integers, I see no use in that). Instead, you should use Integer
, as follows:
ArrayList<Integer> arl = new ArrayList<Integer>();
For adding elements, just use the add
function:
arl.add(1); arl.add(22); arl.add(-2);
Last, but not least, for printing the ArrayList
you may use the build-in functionality of toString()
:
System.out.println("Arraylist contains: " + arl.toString());
If you want to access the i element, where i is an index from 0 to the length of the array-1, you can do a :
int i = 0; // Index 0 is of the first element System.out.println("The first element is: " + arl.get(i));
I suggest reading first on Java Containers, before starting to work with them.
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