java - generics collections.mixin raw and generic type. Integer -> String - exception but String -> Integer works good -


i confusing 2 code snippets:

snippet 1

    list list = new arraylist();     list.add("1");     iterator<integer> iterator = list.iterator();     system.out.println(iterator.next()); 

this code executes , outs 1 console

snippet 2

    list list = new arraylist();     list.add(1);     iterator<string> iterator = list.iterator();     system.out.println(iterator.next()); 

result of - runtimeexception

java.lang.classcastexception: java.lang.integer cannot cast java.lang.string 

i confusing because both these rows wrong:

    integer integer = "123";     string  string = 1; 

it compile error.

why generis behaviour different?

p.s.

i prepare scjp exam , don't mix raw type , generics;

printstream, class of system.out, has number of println overloads. in particular, has an overload takes object , an overload takes string.

in first example,

list list = new arraylist(); list.add("1"); iterator<integer> iterator = list.iterator(); system.out.println(iterator.next()); 

the compiler expects iterator.next() produce integer, , best match object version of println. compiler generates call object version of method, happens work fine string comes out of iterator.

in second example,

list list = new arraylist(); list.add(1); iterator<string> iterator = list.iterator(); system.out.println(iterator.next()); 

the compiler expects iterator.next() produce string, , best match string version of println. compiler generates call string version of method, , due type erasure (which makes runtime type of iterator.next() object), generates runtime cast object string. cast fails integer comes out of iterator, causing exception see.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -