0

Why the following code throws ArrayStoreException on line 3:

int[] ar = {2, 4};
List list = Arrays.asList(ar);
list.set(0, 3);

Unboxing should be performed here from Integer to int but it doesn't.

Artem S
  • 11
  • 3
  • [How to convert int array into List in Java?](https://stackoverflow.com/questions/1073919/how-to-convert-int-into-listinteger-in-java) – Eklavya Sep 24 '20 at 07:24

1 Answers1

1

You're assuming that Arrays.asList(ar) creates a List<Integer>, but that's wrong. Arrays.asList(int[]) creates a List<int[]>, and setting an element of type int in that array explains the ArrayStoreException (saving an int in an int[] array).

If you want a List<Integer> with the same code, declare ar as Integer[]. This is probably another lesson to avoid using raw types (because the compiler would have prevented this runtime exception, had List<Integer> been used as the data type of list)

ernest_k
  • 44,416
  • 5
  • 53
  • 99
  • thank you for your answer. yes I expected that auto boxing should be performed and array of primitives transfers to array of wrappers. – Artem S Sep 24 '20 at 11:49