Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList of int array in java

Tags:

java

arraylist

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:

  1. How to display the correct value i.e. 1 2 3.
  2. How can I access the single element of array a1 i.e. if I want to know the value at a1[1].
like image 317
amv Avatar asked May 07 '12 06:05

amv


1 Answers

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.

like image 182
Raul Rene Avatar answered Sep 19 '22 13:09

Raul Rene