• 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
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

(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!).
 
I am not young enough to know everything. - Oscar Wilde This tiny ad thinks it knows more than Oscar:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic