• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Question about Strings and Hash Code

 
Ranch Hand
Posts: 203
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I encountered the following code and explanation in Core Java2 ( page 97 )

The hashcode for both strings is same and the hashcode for both the string buffers will be different from each other. The explanation is that the hashcode of the String object is based on the contents of the String . And the hashcode of the StringBuffer is basically calculated by the hashCode() function of the Object class, which uses the memory address to calculate the hash code.
I thought that the compiler will encounter two identical String literals and therefore, both Strings s and t refer to the same memory location and so their hash codes are identical.
Can someone shed more light on this ?
TIA
 
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think you're both right:
Notice that java.lang.StringBuffer doesn't override the .hashCode() method -- so it will be determining the hashCode() as if it were an Object.
Whereas the java.lang.String class DOES override the .hashCode() method, so it returns the .hashCode() for the String literal.
[ June 03, 2002: Message edited by: Jessica Sant ]
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Shivaji Marathe:
I thought that the compiler will encounter two identical String literals and therefore, both Strings s and t refer to the same memory location and so their hash codes are identical.


s and t would even have identical hashcodes if refering to different memory locations. Try it with t = new String(s);
sb and tb don't (necessarily) have identical hashcodes, even with identical string content.
Notice that the implementation of Object.hashCode() doesn't need to use the memory location - it's just an implementation detail of the current JVM.
 
reply
    Bookmark Topic Watch Topic
  • New Topic