Casting generics list in Java -


i found weird situation when casting generics. run code:

class { }  class b { }  public class program {      @suppresswarnings("unchecked")     public static void main(string[] args) {         list<a> lista = new arraylist<a>();         list<?> list = lista;         ((list<b>)list).add(new b());          (object item : lista) {             system.out.println(item.tostring());         }     } } 

it compiles (only warning without error) , run without exception , output was:

b@88140ed

how did that? mean why java allow me such thing? added instance of b class list of as?

it bad behaviour of generics. why happening?

btw, tried java 7.

edit:
surprised me java notify problem warning every programmer can ignore it. know suppresswarnings bad idea, why java didn't denied such behavior error or exception?

in addition, warning showed always, if think casting correct have no choice ignore it. if think casting , ignore isn't?

every programming language allows shoot foot.

in case, java in dilemma: keep generics information in bytecode , break millions of lines of existing code or silently drop generics information after compiler has it's utmost check , keep backward compatibility.

the java team decided latter , introduced type erasure - which has flaws. if had broken millions of fine (if type-wise incomplete) lines of java code, people have shown pitchforks , burning torches ...


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -