Question
Why doesn't Arrays.asList() convert an int array to a List of Integers?
int[] ints = new int[] {1, 2, 3, 4, 5};
List<Integer> list = Arrays.asList(ints);
Answer
The issue stems from the fact that the Arrays.asList() method treats an array reference as a single object when it's an int array, rather than the individual elements within that array. This means that when attempting to convert an int[] to a List, the method only sees the array itself, not its contents, which is a common point of confusion when working with primitive types in Java.
// Method 1: Manual Conversion
int[] ints = new int[]{1, 2, 3, 4, 5};
// Create an Integer[] to hold the values
Integer[] integerArray = new Integer[ints.length];
for (int i = 0; i < ints.length; i++) {
integerArray[i] = ints[i];
}
List<Integer> listFromArray = Arrays.asList(integerArray);
// Method 2: Using Streams
List<Integer> listFromStream = IntStream.of(ints).boxed().collect(Collectors.toList());
Causes
- Primitive arrays like int[] are handled differently in Java compared to Wrapper classes.
- Arrays.asList() accepts variable arguments (varargs). When passing an array like int[], it sees it as one entity rather than unpacking the elements.
Solutions
- Convert the primitive int array to a wrapper Integer array using manual conversion or utility methods.
- Use `java.util.stream.IntStream` for a more idiomatic way to convert int[] to List<Integer>.
Common Mistakes
Mistake: Trying to use Arrays.asList() directly with an int array.
Solution: Convert the int array to an Integer array or use streams.
Mistake: Assuming autoboxing will occur with primitive arrays.
Solution: Understand that autoboxing occurs with individual primitive elements but not with arrays.
Helpers
- Arrays.asList()
- int array to List<Integer>
- Java primitive arrays
- Java collections
- autoboxing in Java
- convert int[] to List