tags:

views:

185

answers:

2

How do I convert an array to a list in Java?

I used the Arrays.asList() but the behavior (and signature) somehow changed from 1.4.2 to 1.5.0 and most snippets I found on the web use the 1.4.2 behaviour.

For example:

int[] spam = new int[] { 1, 2, 3 };
Arrays.asList(spam)
  • on 1.4.2 returns a list containing the elements 1, 2, 3
  • on 1.5.0 returns a list containing the array spam

In many cases it should be easy to detect, but sometimes it can slip unnoticed:

Assert.assertTrue(Arrays.asList(spam).indexOf(4) == -1);
+3  A: 

The problem is that varargs got introduced in Java5 and unfortunately, Arrays.asList() got overloaded with a vararg version too. So Arrays.asList(spam) is understood by the Java5 compiler as a vararg parameter of int arrays :-(

This problem is explained in more details in Effective Java 2nd Ed., Chapter 7, Item 42.

Péter Török
I understand what happened, but not why it is not documented. I am looking for an alternative solution without reimplementing the wheel.
Alexandru
Thank you for pointing to the book.
Alexandru
+8  A: 

In your example, it is because you can't have a List of a primitive type. In other words, List<int> is not possible. You can, however, have a List<Integer>.

Integer[] spam = new Integer[] { 1, 2, 3 };
Arrays.asList(spam);

That works as expected.

Joe Daley
@Joe `you can't have a List of a primitive type` - Chuck Norris can :D http://practicinggeek.blogspot.com/
c0mrade