• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt on wildcards in generics

 
Dinesh Tahiliani
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1) List<?> list = new ArrayList<Dog>();
2) List<? extends Animal> aList = new ArrayList<Dog>();
3) List<?> foo = new ArrayList<? extends Animal>();
4) List<? extends Dog> cList = new ArrayList<Integer>();
5) List<? super Dog> bList = new ArrayList<Animal>();
6) List<? super Animal> dList = new ArrayList<Dog>();

Hello Ranchers,
Can you please explain me the above wildcards?
I am facing problem to understand
 
Deepak Chopra
Ranch Hand
Posts: 433
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi As per my understanding:
Generics are for compile time only,so at the compile time javac need to settle every thing, so when you write following:
/************************************************************/
1) List<?> list = new ArrayList<Dog>();
Compiler consider both <?> (on the LHS) and <Dog> (on the RHS)
<?> ---> anything that extends Object ---> So right hand side must comply with this and also it should confirm (means no ? on RHS in most of the cases)
as Dog extends Animal extends Object..So this compiles fine.
/*********************************************************/
2) List<? extends Animal> aList = new ArrayList<Dog>();
LHS(Left hand side):
< ? extends Animal > ---> Anything that extends Animal
Dog --> extends Animal --> compiles fine
/*********************************************************/
3) List<?> foo = new ArrayList<? extends Animal>();
<?> ---> anything extends Object
<? extends Animal> ---> Anything extends Animal (ahh.. nothing is sure..)
So should not compile
/*********************************************************/
4) List<? extends Dog> cList = new ArrayList<Integer>();
<? extends Dog> ---> anything extends Dog
<Integer> ---> doesn't extends Dog..so compiler error..
/*********************************************************/
5) List<? super Dog> bList = new ArrayList<Animal>();
<? super Dog> --> anything which is Superclassof Dog
<Animal> --> it is super class of Dog
so no problem.
/*********************************************************/
6) List<? super Animal> dList = new ArrayList<Dog>();
<? super Animal> -->anything which is super class of Animal
<Dog> --> Dog is subclass of animal not super class..!!
/*********************************************************/
 
Dinesh Tahiliani
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for expalining.
Now i got..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic