• 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

Mixing Generics and Legacy code question

 
Greenhorn
Posts: 4
Mac OS X VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Output: hello

I understand that Legacy List can add any Object. But after coming out of function, why is able to get String and print out (while it is )


[HENRY: enabled code tags]
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

As you already noticed, don't mix generics with non-generics -- generics can break.

Henry
 
Rahul Spark
Greenhorn
Posts: 4
Mac OS X VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks. Can you please explain why it is not giving ClassCastException while printing String from List<Integer>?

My question is more for certification point of view and for better understanding this. Thanks again.
 
Saloon Keeper
Posts: 15524
364
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The compiler expects to retrieve an Integer, for which the PrintWriter has no special method, so the compiler chooses the println() method that has the Object argument, which works equally well for the String retrieved.
 
Rahul Spark
Greenhorn
Posts: 4
Mac OS X VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Stephan

Infact below code gave ClassCastException

 
Stephan van Hulst
Saloon Keeper
Posts: 15524
364
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, because it tries to cast the reference to an Integer, which it's clearly not.

In the former case, it casts the reference to an Object. This is perfectly fine.
 
reply
    Bookmark Topic Watch Topic
  • New Topic