File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics doubt" Watch "Generics doubt" New topic

Generics doubt

Filipe Pinheiro

Joined: Oct 08, 2009
Posts: 9
Hello folks,

I have not understood why the following statement doesn't generate a compile warning:

But, this does:

Looking foward an answer,

Sudhakar Sharma
Ranch Hand

Joined: Apr 04, 2009
Posts: 71

I think "List L=new ArrayList<Integer>();" will first create a Arraylist of Integer typed class then upcast to the type of Object, which is default. but whenever you are trying like "List<Integer> L=new ArrayList();" it will try to create a Object typed ArrayList first then try to set them into a Integer type List.
In first case it will compile and show a warnning conserning about you list is no more type-safed. But in second case compiler will generate an error.
Edwin Dalorzo
Ranch Hand

Joined: Dec 31, 2004
Posts: 961
This does not generate a compiler error, just a warning, though.

This is like this because Java did not have generics until JDK1.5, and they wanted that legacy code were compatible with new generics code. Therefore, if you had libraries returning raw types or receiving raw types as parameters, the Java Programming Language should still work.

This practice though is not recommended for new code written for JDK15 or superior. What you did should have been done like this

A list like this can accept any kind of list and since it uses an unbounded wildcard it will not generate a warning, as it does your legacy code.
Sudhakar Sharma
Ranch Hand

Joined: Apr 04, 2009
Posts: 71

Thank you Edwin for the crystal clear answer.
Dieter Quickfend

Joined: Aug 06, 2010
Posts: 543

Assigning a generic collection to a raw type is not exactly good practice, but it's not dangerous either. Whatever you get out of that collection, you're gonna have to cast it anyway.

Now, if you assign a raw type to a Generic Collection, you're looking at unexpected ClassCastExceptions at runtime. Hence the warning.

Oracle Certified Professional: Java SE 6 Programmer && Oracle Certified Expert: (JEE 6 Web Component Developer && JEE 6 EJB Developer)
I agree. Here's the link:
subject: Generics doubt
It's not a secret anymore!