2

Using Java 1.8, when I do the following:

final int[] weights = { 812, 123, 442, 321, 322, 242, 555 };
final ArrayList list = new ArrayList();
for(int i : weights)
{
    list.add(i);
}

using that ArrayList works as expected. However, if I do this:

final int[] weights = { 812, 123, 442, 321, 322, 242, 555 };
final ArrayList list = new ArrayList(Arrays.asList(weights));

using the ArrayList in the exact same way as for the above, I get

ClassCastException: [I cannot be cast to java.lang.Integer

From here Create ArrayList from array it seems to me as what I am doing in the second case is correct, so why do I get the exception?

It should also be noted that NB 8 warns me that "Confusing primitive array passed to vararg method" for the second instantiation of ArrayList above. Anyone have a clue what's going on?

Community
  • 1
  • 1
OppfinnarJocke
  • 1,038
  • 2
  • 9
  • 21
  • There is no autoboxing for `int[]` to `Integer[]`. Also [generics don't support primitive types](http://stackoverflow.com/q/2721546/1393766) so `T` in `Arrays.asList(T...)` represents `int[]` not `Integer` which means that it will return `List` not `List`. – Pshemo Oct 19 '14 at 17:14
  • Try specifying the data type of your arraylist ==>>. Arraylist – z atef Oct 19 '14 at 17:22
  • @NullSoulException there is no `` in Java. Also there is no `` because generics don't support primitive types. Also there is no point in explicitly using `` to store ``. – Pshemo Oct 19 '14 at 18:15

0 Answers0