javacompareequalshashcodehash-code-uniqueness

Object Identity and Equality in Java


Please take a look at the 2 examples below:

String a = new String("hello");
String b = new String("hello");
System.out.println("a.hashCode() - " + a.hashCode());
System.out.println("b.hashCode() - " + b.hashCode());
System.out.println("a == b - " + (a == b));
System.out.println("a.equals(b) - " + (a.equals(b)));

Result:

a.hashCode() - 99162322
b.hashCode() - 99162322
a == b - false
a.equals(b) - true

If I understand it correctly, I have 2 different objects, since word new creates object. But we see that the hashCode is the same, which means I was wrong. If the hashCode is the same, I understand why a.equals(b) is True.

However the output of this code:

int [] a = {1, 2, 3};
int [] b = {1, 2, 3};
System.out.println("a.hashCode() - " + a.hashCode());
System.out.println("b.hashCode() - " + b.hashCode());
System.out.println("a == b - " + (a == b));
System.out.println("a.equals(b) - " + (a.equals(b)));

is different:

a.hashCode() - 1627674070
b.hashCode() - 1360875712
a == b - false
a.equals(b) - false

Now we have two different objects, because the hashCode is different and that is why both conditions are False (which is how it should be).

Feels like I need to fill the knowledge gap and will appreciate any guidance.

Thanks in advance!


Solution

  • The perceived problem here lies in your understanding of the hashCode-method and the equals method for arrays.

    The hashCode method can be found in Object and will create a hash based on the objects reference.

    The String class overrides this method with its own logic based on calculations done on the chars of the String (more precisely it calculates the hash with the formula s[0]*31^(n - 1) + s[1]*31^(n - 2) + ... + s[n - 1] where s[i] is the i-th character of the String). This means that for 2 Strings that equal each other you will always get the same result by calling hashCode.

    The int[] instead uses the implementation in Object therefore creating the hash from the object reference. This means that for 2 arrays with equal values you will still get a different result by calling hashCode.

    Also to compare the values of two arrays use Arrays.equals as calling int[].equals is the same as using the == operator which goes - once again - for reference comparison. Arrays.equals instead calls the equals method on every element in the array and will return a result based on their equality.