Home >Java >javaTutorial >Why Does Arrays.asList() Misbehave with Primitive Arrays in Java?

Why Does Arrays.asList() Misbehave with Primitive Arrays in Java?

Susan Sarandon
Susan SarandonOriginal
2024-12-20 01:13:08782browse

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 instead of 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 using Arrays.asList().

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 from an array of primitives, you can use third-party libraries that provide additional functionality, such as Guava's com.google.common.primitive.Ints.asList() method. This method explicitly creates a List wrapper around the int[] array, where each element is boxed as an Integer.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn