• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Difference?

 
zainu Mehmood
Ranch Hand
Posts: 45
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

Bit confused so can you please tell me what is really happening here behind the scenes.

Scenrio 1 :



Scenrio 2 :



Specifically what does List<?> really doing here.

sorry if its a dumb question!

BR



 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's say

scenario1:
List<Object> aObj = new ArrayList<Object>(); // generics are invariant

now you try to do a cast to List<Test> as in List<Test> aTestList = (List<Test>)aObj ;
here -> aObj can contains Object which is super class of Test so you will be in trouble here after if the cast is Ok hence error at compile time

scenario2:
List<?> aObj1 = new ArrayList<Test>(); for better understanding consider below assignment
List<? extends Object> aObj1 = new ArrayList<Test>(); //List<?> is similar to List<? extends Object>

now List<?> or List<? extends Object> points to List<Test> , mean while List<? extends Object> can also points to List<Object> i.e,
List<? extends Object> aObj1 = new ArrayList<Object>();

So compiler assume that, (List<?>)aObj this means you are casting List<Object> to List<? extends Object> which can legally point List<Test>
so allowed the following cast (List<Test>)((List<?>)aObj)

not at all dumb question
<edit>corrected typo List<T> to List<Test></edit>
 
zainu Mehmood
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Excellent explanation Mr.Seetharaman. Thanks a lot .
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
zainu Mehmood wrote:Thanks a lot

you are welcome
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic