Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

If the hashCode() method is not overridden, what will be the result of invoking hashCode() on any object in Java?

share|improve this question
    
check out System.identityHashCode() it gives you the default hashcode - the one that would have been returned if you had not overridden the method. –  Ustaman Sangat Dec 14 '11 at 15:58
add comment

9 Answers

up vote 12 down vote accepted

Typically, hashCode() just returns the object's address in memory if you don't overload it.

From 1:

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

share|improve this answer
2  
I have strong objection to "converting the internal address" and I have been wondering if Sun/Oracle will remove that line from their javadocs. Internal address of the object cannot be guaranteed to remain unchanged in the JVM, whose garbage collector might move it around during heap compaction. –  Ustaman Sangat Dec 14 '11 at 15:13
add comment

The implementation of hashCode() may differ from class to class but the contract for hashCode() is very specific and stated clearly and explicitly in the Javadocs:

Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

hashCode() is closely tied to equals() and if you override equals(), you should also override hashCode().

share|improve this answer
    
"hashCode() is closely tied to equals() and if you implement one, you should implement the other" is not entirely correct. You only need to override hashCode if equals is overridden. It is technically valid to override hashCode without overriding equals. –  Steve Kuo Feb 11 '10 at 3:09
    
@Steve Kuo: Fair enough. I re-worded the last sentence based on your comment. –  Asaph Feb 11 '10 at 4:54
add comment

If hashcode is not overriden you will call Object's hashcode, here is an excerpt from its javadoc:

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

share|improve this answer
add comment

A hashcode is useful for storing an object in a collection, such as a hashset. By allowing an Object to define a Hashcode as something unique it allows the algorithm of the HashSet to work effectively.

Object itself uses the Object's address in memory, which is very unique, but may not be very useful if two different objects (for example two identical strings) should be considered the same, even if they are duplicated in memory.

share|improve this answer
add comment

the default hashcode implementation gives the internal address of the object in the jvm, as a 32 bits integer. Thus, two different (in memory) objects will have different hashcodes.

This is consistent with the default implementation of equals. If you want to override equals for your objects, you will have to adapt hashCode so that they are consistent.

See http://www.ibm.com/developerworks/java/library/j-jtp05273.html for a good overview.

share|improve this answer
add comment

Two objects with different hash code must not be equal with regard to equals()

a.hashCode() != b.hashCode() must imply !a.equals(b)

However, two objects that are not equal with regard to equals() can have the same hash code. Storing these objects in a set or map will become less efficient if many objects have the same hash code.

share|improve this answer
add comment

returns 6 digit hex number. This is usually the memory location of the slot where the object is addressed. From an algorithmic per-se, I guess JDK does double hashing (native implementation) which is one of the best hashing functions for open addressing. This double hashing scheme highly reduces the possibility of collisions.

The following post will give a supportive idea -

Java - HashMap confusion about collision handling and the get() method

share|improve this answer
add comment

You should try to implement the hash code so that different objects will give different results. I don't think there is a standard way of doing this.

Read this article for some information.

share|improve this answer
add comment

Not really an answer but adding to my earlier comment

internal address of the object cannot be guaranteed to remain unchanged in the JVM, whose garbage collector might move it around during heap compaction.

I tried to do something like this:

public static void main(String[] args) {
    final Object object = new Object();
    while (true) {
        int hash = object.hashCode();
        int x = 0;
        Runtime r = Runtime.getRuntime();
        List<Object> list = new LinkedList<Object>();
        while (r.freeMemory() / (double) r.totalMemory() > 0.3) {
            Object p = new Object();
            list.add(p);
            x += object.hashCode();//ensure optimizer or JIT won't remove this
        }
        System.out.println(x);
        list.clear();
        r.gc();
        if (object.hashCode() != hash) {
            System.out.println("Voila!");
            break;
        }
    }
}

But the hashcode indeed doesn't change... can someone tell me how Sun's JDK actually implements Obect.hashcode?

share|improve this answer
    
OpenJDK hg.openjdk.java.net/jdk6/jdk6-gate/jdk/file/tip/src/share/… has it as a native function. I would like to see the native function implementation...stackoverflow.com/questions/410756/…. Anyone? –  Ustaman Sangat Dec 14 '11 at 15:54
    
Maybe the default hashcode method stores the first value and never changes it. –  Ustaman Sangat Dec 14 '11 at 18:28
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.