java - Are we allowed to use wildcard during instantiation -


why these declaration invalid in java?

  1. list<number> test = new arraylist<? extends number>();

  2. list test = new arraylist<? extends number>();

are not allowed use wildcard during instantiation. , if wildcards useful passing them methods?

and list<object> test = new arraylist<integer>(); illegal because generics not covariant correct?

the ? wildcard character means "unknown" not "any". doesn't make sense instantiate new container of unknown contents, put in there? can't used anything!

so declaraion new arraylist<? extends number>() means "some specific thing extends number, don't know what." does not mean "anything extends number."
list<number> assigned allow both double , integer added it, actual contents of list<? extends number> might float! (or whatever else.) consider happen in code if wildcard worked "any":

    list<integer> listinteger = new arraylist<integer>();     listinteger.add(integer.valueof(1));     list<? extends number> listwildcard = listinteger;     listwildcard.add(double.valueof(1.0)); //this not compile     integer integer = listinteger.get(1);//because throw classcastexception 

footnote regarding second example: declaring paramaterized type no type parameter called using raw type. considered programming error. syntax legal code written before java 5 still compiles. don't if scenario isn't backward compatability pre-java 5.


Comments

Popular posts from this blog

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

html - How to style widget with post count different than without post count -

url rewriting - How to redirect a http POST with urlrewritefilter -