Why doesn’t Java convert int [] to integer []

When I do the following things,

>Arraylist1 – contains an element that is an int []. > Arraylist2 – not compiling (error: constructor ArrayList < integer > (list < int [] >) is undefined) > arraylist3 – contains 7 elements, which are integer objects

Here are the codes:

int[] intArray = new int[]{2,3,4,5,6,7,8};
ArrayList arrayList1 = new ArrayList(Arrays.asList(intArray));
ArrayList<Integer> arrayList2 = new ArrayList<Integer>(Arrays.asList(intArray));

Integer[] integerArray = new Integer[]{2,8};
ArrayList<Integer> arrayList3 = new ArrayList<Integer>(Arrays.asList(integerArray));

Question: why doesn't the compiler automatically copy the elements in int [] to integers and create an ArrayList < integer >? What's the reason? Is it my stupidity or something else?

Solution

The difference is that int [] itself is an object, while integer [] is an array referencing integer objects

Arrays. asList(T...) Method accepts some variables of type T without an upper bound The erasure of this method is arrays asList(Object …). This means that it will extend a variable number of parameters of any type from object

Because int is not an object, but a primitive type, it cannot be passed as a separate element of T []. Int [] is an object itself, which will be the first element of the T [] array (t... There is only a T []) However, integer [] will be passed as t [], and each reference passes integer [] as a different parameter to t []

Even if you think the compiler should have completed the conversion from each element of the int [] array to integer, this will be too much work for the compiler First, you need to use each array element and wrap it into an integer, and then you need to create an integer [] There are too many. It already has a direct conversion from int [] to object Although I have always hoped that Java allows implicit conversion from int [] to integer [], it will make life easier when using generic code, but how does this design the language

Take a simple example:

Object[] array = new Integer[10];  // this is valid conversion
Object[] array2 = new int[10];     // this is not
Object obj = new int[10];          // this is again a valid conversion

So in your code, arrays Aslist (int array) returns an ArrayList < int [] > instead of ArrayList < integer > You cannot pass it to the ArrayList < integer > () constructor

of

> int[] and Integer[]: What is the difference?

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>