• 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

(String) vs toString()

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello guys:
Talking about casting when you extract String objects from a HashMap or any object collection.
Whats the difference between:


and

And wich one is the correct way ?
Thanks in advanced.
C. Olmos.
 
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by carlos olmos:
And wich one is the correct way ?


Well, which one is correct really depends on what you have in your collection. The first method you showed (using a cast) works great if what's in the collection really is a String. However, if you had something else in there, like an Integer, you'd get a ClassCastException at runtime. In that case, you'd want to use the toString method of Integer (or whatever other object you have in there) in order to get a textual representation of that object.
I hope that helps,
Corey
 
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

... when you extract String objects from a HashMap ...


In this case both approaches are correct. toString() method, return the String itself (this), and the cast is a perfectly valid cast (once again: if you are certain that you have String objects in the Map!).
 
reply
    Bookmark Topic Watch Topic
  • New Topic