Arrays.asList return type confusion mismatch

Why doesn't the following return a list of integers?

int[] ints = new int[] { 1, 2, 3, 4, 5 }; List<Integer> intsList = Arrays.asList(ints); //compilation error 

Instead, instead of an int[] list

So far this

 String[] strings = new String[] { "Hello", "World" }; List<String> stringsList = Arrays.asList(strings); 

Returns a list of String . I assume this fails because it is an array of primitives, but why? And how do I really return an int list.

+4
source share
3 answers

T in List<T> should be some subtype of java.lang.Object , which int not. Only a different interpretation is used, since we use ... that you supply an array of int[] , that is, int[][] . So you get List<int[]> .

String is a subtype of Object , so this works as expected. Also the only way it can work before introducing varargs in J2SE 5.0. Typically, the interpretation of existing code should not be changed between language versions.

Now, if you want a List<Integer> , you can go through and put each integer. If your program has a lot of these elements, then a memory problem may arise. You can use a third-party library that compactly supports List<Integer> with int[] , or just stick with arrays for primitives. It is regrettable that Java does not support value types.

+2
source

This is because Arrays.asList(new int[] { 1, 2, 3, 4, 5 }) will create a List<int[]> with one element, not a List<Integer> with five elements.

Note that this will do what you expected:

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

Your other alternatives:

  • to create an Integer[] first or
  • to populate your list in a loop
+7
source

The method is defined as: public static <T> List<T> asList(T... a)

So, in your first case, T is int[] , and you pass one object to the method (i.e. an array), so it returns an int[] list.

I think you are mistaken with asList(1, 2, 3, 4, 5) (i.e. 5 elements)

+3
source

Source: https://habr.com/ru/post/1484481/


All Articles