Converting array to list in Java
How do I convert an array to a list in Java?
I used the Arrays.asList()
but the behavior (and signature) somehow changed from Java SE 1.4.2 (docs now in archive) to 8 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)
In many cases it should be easy to detect, but sometimes it can slip unnoticed:
Assert.assertTrue(Arrays.asList(spam).indexOf(4) == -1);
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.
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.
Speaking about conversion way, it depends on why do you need your List
. If you need it just to read data. OK, here you go:
Integer[] values = { 1, 3, 7 };
List<Integer> list = Arrays.asList(values);
But then if you do something like this:
list.add(1);
you get java.lang.UnsupportedOperationException
. So for some cases you even need this:
Integer[] values = { 1, 3, 7 };
List<Integer> list = new ArrayList<Integer>(Arrays.asList(values));
First approach actually does not convert array but 'represents' it like a List
. But array is under the hood with all its properties like fixed number of elements. Please note you need to specify type when constructing ArrayList
.
上一篇: 堆栈被@autoreleasepool破坏(ARC,使用llvm 3.0编译,Fastest,Smallest [
下一篇: 在Java中将数组转换为列表