Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayLists and indexers in Java

Is it possible to do this in Java? Maybe I'm using the wrong syntax?

ArrayList<Integer> iAL = new ArrayList<Integer>();
iAL.addAll(Arrays.asList(new Integer[] {1, 2, 3, 4, 5 }));

for (int i = 0; i < iAL.size(); ++i) {
    System.out.println(iAL[i]); //<-------- HERE IS THE PROBLEM
}

Also, is it possible to do something like

iAL.addAll( new int[] {1, 2, 3, 4, 5} );

as is seen on c#?

Thanks

like image 569
devoured elysium Avatar asked Feb 28 '10 15:02

devoured elysium


2 Answers

Try System.out.println(iAL.get(i));. Because it's a List, not array

like image 156
Igor Artamonov Avatar answered Sep 28 '22 03:09

Igor Artamonov


ArrayList<Integer> iAL = new ArrayList<Integer>();
iAL.addAll(Arrays.asList(new Integer[] {1, 2, 3, 4, 5 }));

for (int i = 0; i < iAL.size(); ++i) {
    System.out.println(iAL.get(i)); 
}

AFAIK

iAL.addAll(Arrays.asList(new Integer[] {1, 2, 3, 4, 5 })); // this is the shortest solution

like image 38
Anantha Kumaran Avatar answered Sep 28 '22 03:09

Anantha Kumaran