1

Small question.

String s1 = "test";
String s2 = "test";

s1,s2 both have same hashCode value

String sn1 = new String("java");
String sn2 = new String("java");

all of them said sn1 and sn2 have different hashCode values and those are different objects

When I am printing hashCode values it gives same value that means sn1 and sn2 points to the same object or not ?

PakkuDon
  • 1,629
  • 4
  • 22
  • 21
CHAITHANYA PADALA
  • 147
  • 1
  • 1
  • 8

4 Answers4

3

Hash codes should be equal if objects are equal (the reverse is not true, however). Since

  sn1.equals(sn2) // true

We can conclude that

  sn1.hashCode() == sn2.hashCode() // true
Dmitry Bychenko
  • 165,109
  • 17
  • 150
  • 199
1

It is often useful to look at the java code to see what is happening.

For example the String#hashCode method

public int hashCode() {
    int h = hash;
    if (h == 0) {
        int off = offset;
        char val[] = value;
        int len = count;

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

As you can see the result is based upon the value of the String, not its memory location.

Scary Wombat
  • 43,525
  • 5
  • 33
  • 63
1

If you are comparing Strings like:

s1 == s2

then you're comparing the pointer (the reference) of the String. This reference is not what you're getting from the String#hashCode method.

If you are comparing Strings like:

s1.equals(s2)

then the method String#equals uses the String#hashCode methods of both Strings and compares the results.

Try it out by yourself:

public class StringEquality {
    public static void main(String[] args) {
        String s1 = new String("java");
        String s2 = new String("java");

        // hashCodes
        System.out.println(s1.hashCode());
        System.out.println(s2.hashCode());

        // equality of hashCodes
        System.out.println(s1.equals(s2));

        // references
        System.out.println(System.identityHashCode(s1));
        System.out.println(System.identityHashCode(s2));

        // equality of references
        System.out.println(s1 == s2);
    }
}

Will print something like:

3254818
3254818
true
1072624107
1615633431
false
bobbel
  • 3,239
  • 2
  • 25
  • 41
0

All of who? sn1 and sn2 are different objects, but they are identical, so they have the same hash code.

Dawood ibn Kareem
  • 73,541
  • 13
  • 95
  • 104