This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft 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 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics - When are warnings shown" Watch "Generics - When are warnings shown" New topic
Author

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: 171
    
    5

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: http://aspose.com/file-tools
 
subject: Generics - When are warnings shown
 
Similar Threads
compareTo()
doubt in generics in java 1.5
Generics - super
ArrayList confusion
remove the element in list while iterating through it.