generics collections.mixin raw and generic type. Integer -> String - exception but String -> Integer works good
casting, generics, java, type-conversion, type-erasure
Solution
`PrintStream`, the class of `System.out`, has a number of `println` overloads. In particular, it has an overload that takes an `Object` and an overload that takes a `String`.
In the first example,
List list = new ArrayList();
list.add("1");
Iterator<Integer> iterator = list.iterator();
System.out.println(iterator.next());
the compiler expects `iterator.next()` to produce an `Integer`, and the best match for that is the `Object` version of `println`. The compiler generates a call to the `Object` version of the method, which happens to work just fine for the `String` that actually comes out of the iterator.
In the second example,
List list = new ArrayList();
list.add(1);
Iterator<String> iterator = list.iterator();
System.out.println(iterator.next());
the compiler expects `iterator.next()` to produce a `String`, and the best match for that is the `String` version of `println`. The compiler generates a call to the `String` version of the method, and due to type erasure (which makes the runtime type of `iterator.next()` `Object`), it generates a runtime cast from `Object` to `String`. This cast fails for the `Integer` that actually comes out of the iterator, causing the exception you see.
Problem
I am confusing with two code snippets: snippet 1 ``` List list = new ArrayList(); list.add("1"); Iterator<Integer> iterator = list.iterator(); System.out.println(iterator.next()); ``` this code executes normally and outs `1` to console snippet 2 ``` List list = new ArrayList(); list.add(1); Iterator<String> iterator = list.iterator(); System.out.println(iterator.next()); ``` Result of it - RuntimeException ``` java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String ``` I am confusing because both these rows are wrong: ``` Integer integer = "123"; String string = 1; ``` It is compile error. Why does for generis behaviour is different? P.S. I am prepare for scjp exam and don't mix raw type and generics;