I am not exactly sure why the hashCode() method is returning the same value. Can someone provide more detailed explanation of this?
Source code (Java):
public class Equality {
public static void main(String [] args)
{
String str = "String";
String strOne = new String("String");
System.out.println(str == strOne);
System.out.println(str.equals(strOne));
System.out.println(str.hashCode());
System.out.println(strOne.hashCode());
}
}
From the Javadoc :
Basically,
a.equals(b) => a.hashCode() == b.hashCode()
so two identical strings will surely have the same hashCode.It seems to me that the behaviour you were expecting is the one of
==
, but it clearly is not.==
is the strongest equality in Java, because it compares the location in memory of two objects.equals
comes just after it, it is a logical equality, two objects can beequal
even if they have different memory locations. ThehashCode
has the weakest properties, quoted above.