The Javadocs say:
Returns a hashcode for this Method. The hashcode is computed as the exclusive-or of the hashcodes for the underlying method's declaring class name and the method's name.
Conspicuously absent from this description are the types of the Method's parameter types - does this mean that two methods on the same class with the same name, but different parameters, would have the same hashCode()
?
It is because the author is overriding equals. Equals is specified in java. lang. Object and is something that all classes inherrits from.
The purpose of the hashCode() method is to provide a numeric representation of an object's contents so as to provide an alternate mechanism to loosely identify it. By default the hashCode() returns an integer that represents the internal memory address of the object.
The hashCode method for a given class can be used to test for object equality and object inequality for that class. The hashCode method is used by the java. util. SortedSet collection class to order the elements within that set.
If two objects are equal(according to equals() method) then the hashCode() method should return the same integer value for both the objects. But, it is not necessary that the hashCode() method will return the distinct result for the objects that are not equal (according to equals() method).
You are right - methods with the same name and the same declaring class have, as documented, the same hash-code. Which, I agree, is a bit counter-intuitive.
The code in Sun's JDK:
public int hashCode() {
return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
}
But hashCode()
isn't a sign for equality. The equals(..)
method takes into account arguments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With