• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Generics - When are warnings shown

 
Ranch Hand
Posts: 430
Android VI Editor Debian
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 208
9
Eclipse IDE Firefox Browser Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
My name is Inigo Montoya, you killed my father, prepare to read a tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic