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.