This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics - When are warnings shown 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 - When are warnings shown" Watch "Generics - When are warnings shown" New topic

Generics - When are warnings shown

O. Ziggy
Ranch Hand

Joined: Oct 02, 2005
Posts: 430

In chapter 7 page 602/603 in K&B, it explains that for legacy code to work, the compiler will allow you to put anything into a collection but will generate a warning. Why is the following example producing an error instead of a warning.

Thanks in advance.
Tina Smith
Ranch Hand

Joined: Jul 21, 2011
Posts: 208

Because your example doesn' use legacy code.

If you were writing legacy code, you would write

This would generate a compiler warning about raw types, but you'd be allowed to put anything into the list as you describe.

An important thing to understand about generics in Java is they are only applied at compile time. The types running in the JVM would still look like the legacy code above. Since you specify the type of the list, the compiler enforces what you can put into it, e.g. a String "is not" an AnimalA. The compiler will automatically change the code above to which would allow you to put the String in there since String "is a" Object.

Everything is theoretically impossible, until it is done. ~Robert A. Heinlein
I agree. Here's the link:
subject: Generics - When are warnings shown
It's not a secret anymore!