Zhipeng YANG
Zhipeng YANG

Reputation: 807

Why do 2 Object have diff hash codes, but 2 String have the same hash codes in Java?

class A{
    int a;
    A(){
        this.a = 100;
    }
}
//in main, we have:
A a = new A(), b = new A();
//and
String str0 = "123", str1 = "123";

Why do the hash codes of str0 and str1 are the same, but not a and b?

Upvotes: 2

Views: 113

Answers (3)

Crazyjavahacking
Crazyjavahacking

Reputation: 9677

Because the implementation of hashCode() in java.lang.String class is overridden.

In order to be able to use Strings in collections, the implementation has to be overridden.

Upvotes: 2

Michael Hobbs
Michael Hobbs

Reputation: 1693

Because the hashCode implementation for String has been built to always return the same hash code for the the same collection of chars in a given order. Whereas Object.hashCode() treats ever object as unique. If you want to know if two Strings are different object then you could Objects.hashCode(someString)

/**
 * Returns a hash code for this string. The hash code for a
 * {@code String} object is computed as
 * <blockquote><pre>
 * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
 * </pre></blockquote>
 * using {@code int} arithmetic, where {@code s[i]} is the
 * <i>i</i>th character of the string, {@code n} is the length of
 * the string, and {@code ^} indicates exponentiation.
 * (The hash value of the empty string is zero.)
 *
 * @return  a hash code value for this object.
 */
public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}

Upvotes: 1

Anderson Vieira
Anderson Vieira

Reputation: 9049

Because String overrides Object.hashCode() while your class doesn't.

What this means is that the String class has a specific implementation of hashCode() that will calculate a hash based on the String value. So for two strings with the same value, the hash code will be the same.

When you create a new class, A, for example, if you do not provide your own implementation for hashCode() it will use the default implementation from class Object. The default implementation can only guarantee that the hash codes will be the same if they come from exactly the same instance.

The methods Objects.hash() (for multiple values) and Objects.hashCode() (for a single value) make it easier to implement hashCode() in your own classes. For example:

class A{
    int a;

    A() {
        this.a = 100;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(a);
    }
}

Note that if the values of the attributes used to create the hash change at some point, the result of hashCode() will probably change too.

Upvotes: 6

Related Questions