Arrays.asList() and Primitive Arrays
When attempting to convert an array of primitive data into a list using the Arrays.asList() method, one may encounter inconsistencies. This article explores the issue and provides solutions.
Problem Explanation
The Arrays.asList() method accepts variable arguments that represent an array. However, it does not support primitive data types such as int[], unlike reference types like Integer[]. As a result, the second example provided:
int[] ints = new int[] {1,2,3,4,5}; List<Integer> list = Arrays.asList(ints);
returns a List
Autoboxing
Autoboxing, which converts primitive data types to their wrapper counterparts, does not apply to arrays of primitives. Hence, the int[] array is not automatically converted to an Integer[] array.
Solution
To resolve this issue, one can leverage third-party libraries such as Guava's com.google.common.primitive.Ints.asList method. It creates a list of boxed values from a primitive array. Alternatively, one can manually create an Integer[] array and assign values from the int[] array, i.e.,
int[] ints = new int[] {1,2,3,4,5}; Integer[] integers = new Integer[ints.length]; for (int i = 0; i < ints.length; i++) { integers[i] = ints[i]; } List<Integer> list = Arrays.asList(integers);
The above is the detailed content of Why Doesn't Arrays.asList() Work with Primitive Arrays?. For more information, please follow other related articles on the PHP Chinese website!