devoured elysium
devoured elysium

Reputation: 105227

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

Upvotes: 5

Views: 935

Answers (6)

trashgod
trashgod

Reputation: 205885

In addition, I would add two other notes about your code:

For example, combining several helpful suggestions from other answers

List<Integer> list = new ArrayList<Integer>();
list.addAll(Arrays.asList(1, 2, 3, 4, 5 ));

for (Integer i : list) {
    System.out.println(i);
}

Addendum: The question of coding to the interface is interesting, and Carl's comment is particularly apropos. Using the interface type, List, minimizes your obligation to use a specific implementation. If the need arises, you can later switch to any class that implements List.

Upvotes: 3

Carl
Carl

Reputation: 7564

No, you must use .get(i); [i] is for arrays only. However, if you don't need the index variable for something else, the for-each syntax is preferable (as per trashgod's answer).

For the second, if you aren't resizing the List (it is still fine to mutate individual elements), it would be perfectly reasonable to do the following:

List<Integer> iAL = Arrays.asList(1, 2, 3, 4, 5);

Note, that Arrays.asList() accepts a varargs parameter, so no reason to explicitly construct the array.

If you want a resizable List, the following is probably the shortest:

List<Integer> iAL = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5));

Upvotes: 3

missingfaktor
missingfaktor

Reputation: 92116

I will refactor your entire code to :

List<Integer> iAL = Arrays.asList(1, 2, 3, 4, 5 );

for (int i : iAL) {
  System.out.println(i);
}

Upvotes: 2

Konrad Rudolph
Konrad Rudolph

Reputation: 546183

Also, is it possible to do something like

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

Close enough:

iAL.addAll(Arrays.asList(1, 2, 3, 4, 5));

No need for the new Integer[] in your code.

Upvotes: 4

Anantha Kumaran
Anantha Kumaran

Reputation: 10387

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

Upvotes: 4

Igor Artamonov
Igor Artamonov

Reputation: 35961

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

Upvotes: 10

Related Questions