Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Method.hashCode() consider the method's parameter types?

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()?

like image 821
sanity Avatar asked Apr 01 '11 21:04

sanity


People also ask

Why does the equals () method take an object type as its parameter?

It is because the author is overriding equals. Equals is specified in java. lang. Object and is something that all classes inherrits from.

What is the purpose of the hashCode () method?

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.

What is a valid use of the hashCode () method Mcq?

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.

What is the relationship between hashCode () and equals () method in Java?

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).


1 Answers

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.

like image 154
Bozho Avatar answered Oct 06 '22 23:10

Bozho