| Author |
Problem on String
|
Srikanth Nakka
Greenhorn
Joined: Apr 15, 2007
Posts: 26
|
|
Hi all,
I am preparing for SCJP 6 and i have one Question on String see the code below
Output:
hash code for str1: -1704812257
hash code for str2: -1704812257
str1.equals(str2): true
str1 == str2: false
str1 and str2 are pointing to only one reference(same hashcode), so str1 == str2 should be true
Thank you all
|
Thanking You,
Srikanth Nakka
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16680
|
|
str1 and str2 are pointing to only one reference(same hashcode), so str1 == str2 should be true
Hashcodes have nothing to do with there references. With the Object class, they might have been originally generated from the references. With other classes, such as String, Integer, Short, Byte, etc., they have nothing to do with their reference locations.
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Srikanth Nakka
Greenhorn
Joined: Apr 15, 2007
Posts: 26
|
|
Thanks for your help and i have one more doubt that
Hashcodes have nothing to do with there references
so what is the use of hashcode, if you can specify an example that better .
Thanks
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16680
|
|
Srikanth Nakka wrote:
Thanks for your help and i have one more doubt that
Hashcodes have nothing to do with there references
so what is the use of hashcode, if you can specify an example that better .
Thanks
Hashcodes are use by the hashing collections -- Hashtable, HashMap, HashSet, ConcurrentHashMap, etc... See those classes for more information.
Furthermore, the subject of hashing is not specific to Java. You may want to google hashing for more information on the topic.
Henry
|
 |
Jyoti B.Shah
Greenhorn
Joined: Nov 13, 2008
Posts: 17
|
|
Hash code contract states that:
"
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
"
In your example, strings are equal as per the equals() method and therefore they must return same hascode value from the hashCode() method.
Hopefully, this makes sense. Let me know if you have any questions related to what i said.
|
SCJP(95%)
|
 |
Jyoti B.Shah
Greenhorn
Joined: Nov 13, 2008
Posts: 17
|
|
Just adding little more:
Objects are considered equal if they are equal as per the equals() method and not "==" operator. Equals() method(and not ==) is used by hashCode() to determine the hascode for an object.
Also, As per the contract, it is not required for two unequal objects to have different hashcode. In a bad implementation of hascode, you can have same hash code value for two different objects(their euals() method returns false). It is perfectly legal.
|
 |
 |
I agree. Here's the link: jrebel
|
|
subject: Problem on String
|
|
|