Home >Java >javaTutorial >Why Does Arrays.asList() Misbehave with Primitive Arrays in Java?
Why Arrays.asList() Can Be Tricky with Primitives
Java's Arrays.asList() method allows you to convert an array to a List. However, it can behave unexpectedly with primitive arrays.
Question: Why does Arrays.asList(int[]) return a List
Answer: Java generics do not support primitive types. Instead, they use their wrapper classes (e.g., Integer, Float). Arrays.asList() returns a list of the exact same type as the array it is passed. Since int[] is an array of int, the result is List
Question: Is there a way to convert an int[] to a List
Answer: No, there is no direct way to convert an int[] to a List
Question: Why doesn't autoboxing work in this case?
Answer: Autoboxing only occurs for individual primitive values, not for arrays of primitives. Therefore, int[] ints cannot be automatically converted to Integer[].
Solution:
To obtain a List
Alternatively, if you are free to start with an Integer[] array, you can use Arrays.asList() directly as it would return a List
The above is the detailed content of Why Does Arrays.asList() Misbehave with Primitive Arrays in Java?. For more information, please follow other related articles on the PHP Chinese website!