Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In the following examples:

class ZiggyTest2{
    public static void main(String[] args){

        int[] a = { 1, 2, 3, 4,7};      

        List<Integer> li2 = new ArrayList<Integer>();
        li2 = Arrays.asList(a);     

    }
}   

The compiler complains that that int[] and java.lang.Integer are not compatible. i.e.

found   : java.util.List<int[]>
required: java.util.List<java.lang.Integer>
                li2 = Arrays.asList(a);
                               ^

It works fine if i change the List definition to remove the generic types.

List li2 = new ArrayList();
  • Shouldn't the compiler have auto-boxed the ints to Integer?
  • How can i create a List<Integer> object from an array of ints using Arrays.asList()?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
343 views
Welcome To Ask or Share your Answers For Others

1 Answer

Java does not support the auto-boxing of an entire array of primitives into their corresponding wrapper classes. The solution is to make your array of type Integer[]. In that case every int gets boxed into an Integer individually.

int[] a = { 1, 2, 3, 4, 7 };
List<Integer> li2 = new ArrayList<Integer>();
for (int i : a) {
    li2.add(i); // auto-boxing happens here
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...