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!