wood burning stoves 2.0*
The moose likes Java in General and the fly likes Difference? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Difference?" Watch "Difference?" New topic
Author

Difference?

zainu Mehmood
Ranch Hand

Joined: May 09, 2007
Posts: 45
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

Joined: Jan 28, 2008
Posts: 5575

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

Joined: May 09, 2007
Posts: 45
Excellent explanation Mr.Seetharaman. Thanks a lot .
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

zainu Mehmood wrote:Thanks a lot

you are welcome
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Difference?
 
Similar Threads
Generics: subtype convariance issues
Scope and classes/methods
equals hashcode
how to pass the values and how to get the Arraylist table from java script function
Generics: why doesn't this work for extending wildcards?