Reputation: 69
why hashcode value is same?
public static void main(String args[])
{
String s1="abc";
String s2=new String("abc");
System.out.println("Hashcode s1-:"+ s1.hashCode());
System.out.println("Hashcode s2-:"+ s2.hashCode());
if(s1==s2){
System.out.println("==true:");
}
}
output
Hashcode s1-:96354
Hashcode s2-:96354
Upvotes: 0
Views: 996
Reputation: 111369
The hash code for two equal objects should be equal.
In this case, the objects are strings and they are considered equal because they hold the same sequence of characters, "abc".
If you want a hash code that is based on object identity rather than equality use System.identityHashCode()
.
Upvotes: 7
Reputation: 1415
The JVM doesn't create a new String if this already exist, it just returns the reference. A new String will be created when you try to change the actual String in one of the vars. You can check it debugging the application, the String objects will have different memory addresses but the value inside will have exactly the same memory address.
Upvotes: 0
Reputation: 10891
String
class has its own hashcode
method implemeted in it. Its method will compute the hashcode as: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
So for the same character sequence hashcode will be same.
Upvotes: 0
Reputation: 5266
Hashcode for a string is computed based on its characters and so is equals()
It is calculated as
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
where s[i] is each character for 0<=i<n
and n is its length.
Both your strings have the same content and thus hashcode is the same.
Upvotes: 0
Reputation: 6622
as per the rules, objects for those equals method return true, should have the same hashcode.
Upvotes: 0
Reputation: 45080
Because the hashcode is computed using the formula which takes in only the characters present in the string. Same characters in a String
will yield the same hashcode.
Javadoc for the computation formula.
Upvotes: 2
Reputation: 1722
This is the code...therefore the result is the same for two equals objects:
public int hashCode() {
int h = hash;
int len = count;
if (h == 0 && len > 0) {
int off = offset;
char val[] = value;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
Upvotes: 0
Reputation: 10161
Why wouldn't they be the same? The hashcode
is computed on the contents of the string, hence they are the same for both.
==
compares object references, and because you used new String
for s2
the references are not the same.
You should be using the equals
method to test equality of strings based on their value.
Upvotes: 3
Reputation: 10833
This is because of how the hashcode of String
are computed in java.
Check the javadoc : http://docs.oracle.com/javase/6/docs/api/java/lang/String.html
And more over, your two strings are equals, therefore their hashcode must be the same.
Upvotes: 0