Question
Why doesn't my varargs work with ArrayList in Java?
public void doSomething(int... args) {
List<Integer> broken = new ArrayList<Integer>(Arrays.asList(args));
}
Answer
In Java, when you use varargs (variable arguments) with primitive types like `int`, the compiler converts them into an array. However, due to type erasure and the specific way `Arrays.asList` works, when you attempt to convert a primitive `int[]` into a `List<Integer>`, the compiler throws an error because it cannot handle the conversion directly.
public void doSomething(int... args) {
List<Integer> numbers = new ArrayList<>();
for (int arg : args) {
numbers.add(arg);
}
}
Causes
- Using `int...` creates an array of primitives, not a list of objects.
- `Arrays.asList` does not directly support primitive arrays; it expects an array of objects.
Solutions
- Convert the primitive array to an array of `Integer` objects before passing it to `Arrays.asList`.
- Use a loop to add each element of the `int` array to the `ArrayList`.
Common Mistakes
Mistake: Assuming `Arrays.asList(args)` works directly with primitive varargs.
Solution: Explicitly convert varargs to `Integer` before creating the `List` using a loop.
Mistake: Not recognizing that ArrayList cannot take a primitive array directly.
Solution: Use `Integer[]` instead of `int[]` to utilize `Arrays.asList`.
Helpers
- Java varargs
- ArrayList issue Java
- Arrays.asList with varargs
- Java List<Integer>