The problem is that you are skipping generic types so you don't see the error and Java is not able to reject your code even if it's wrong.
The problem is that the signature of Arrays::asList
is asList(T... values)
, but T
can't be a primitive so the variadic arguments are collapsed into an int[]
(which is now an object) and Arrays.asList
returns a List<int[]>
.
Then pass it to a generic HashSet
constructor which then accepts a Collection<Object>
without any problem, and assign it to an HashSet<Integer>
, with the compiler warning you about using raw types.
Finally you try to assign the elements in the hash set (which are of type int[]
) to elements in an Integer[]
array causing the exception, that's like doing
Integer[] data = new Integer[5];
data[0] = new int[] {1, 2, 3};
which is wrong but Java can't realize it at compile time.
If you had constructed the HashSet
through new HashSet<>
then Java compiler would have risen an error. You can solve the issue by passing an Integer[]
to asList
method such that it's correctly treated as variadic arguments.