java - How can an Integer be added to a String ArrayList? -


list list = new arraylist<string>() ; list.add(1) ; integer hello = (integer) list.get(0) ; system.out.println(hello); 

the above code has reference of type list referring instance of arraylist of type string. when line list.add(1) executed, isn't 1 added arraylist (of type string) ? if yes, why allowed?

you have used type erasure, means have ignored set generic checks. can away this generics compile time feature isn't checked @ runtime.

what have same as

list list = new arraylist() ; list.add(1) ; integer hello = (integer) list.get(0) ; system.out.println(hello); 

or

list<integer> list = new arraylist<integer>() ; list.add(1) ; integer hello = list.get(0); // generics add implicit cast here system.out.println(hello); 

if @ byte code generated compiler, there no way tell difference.

interestingly, can this

list<string> strings = new arraylist<string>(); @suppresswarnings("unchecked"); list<integer> ints = (list) strings; ints.add(1);  system.out.println(strings); // ok string s= strings.get(0); // throws classcastexception 

Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -