6

Possible Duplicate:
what is an objects hashcode

Let's say that I create an object, called Employee which has id, firstName, lastName and email for instance variables and corresponding setter/getter methods. How is hashCode() calculated if I don't override hashCode() in Employee object when it is stored in collection objects?

Community
  • 1
  • 1
user826323
  • 2,248
  • 6
  • 43
  • 70

5 Answers5

31

If you don't override hashcode() then the default implementation in Object class will be used by collections. This implementation gives different values for different objects, even if they are equal according to the equals() method.

Some collections, like HashSet, HashMap or HashTable use the hash code to store its data and to retrieve it. If you don't implement hashcode() and equals() in a consistent manner, then they will not function properly.

Edit:

As per Javadoc: Object.hashcode() is ''typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java(TM) programming language''. Therefore I would advise not to rely on a specific implementation. For what the implementations really do, see this answer to a similar question.

Community
  • 1
  • 1
Cyrille Ka
  • 15,328
  • 5
  • 38
  • 58
  • 2
    Note that you cannot count on different objects getting different hashCode values. In particular, a 64-bit JVM could have more objects than there are distinct int values. That will become more practical as memory sizes increase. – Patricia Shanahan Jan 30 '13 at 16:44
9

From the documentation:

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

So basically when you store in a Map/Set/somethingThatRequiresHashCode, the JVM will use the internal memory address of that instance to calculate the hashCode, guaranteeing (as much as hash functions guarantee anything - they don't) that each distinct instance will have a unique hashCode.

This is particularly important because of the Object contract regarding equals and hashCode, since:

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

If you don't override equals, it will compare the internal address of the two references, which matches the logic behind hashCode.

If your question is more related to: Will the JVM look at the values inside an instance to determine equality/calculate hashcode, the answer is simply no, if you do:

MyObject a = new MyObject("a", 123,"something");
MyObject b = new MyObject("a", 123,"something");

a and b will have different hashcodes.

pcalcao
  • 15,789
  • 1
  • 44
  • 64
2

From effective Java 2nd Edition

Item 9: Always override hashCode when you override equals

A common source of bugs is the failure to override the hashCode method. You must override hashCode in every class that overrides equals. Failure to do so will result in a violation of the general contract for Object.hashCode, which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.

I suggest you read that chapter. There are a lot of examples, that you can learn, what will happen if you don't do so.

Community
  • 1
  • 1
Kent
  • 189,393
  • 32
  • 233
  • 301
  • "in conjunction" was the magic term I was looking for, every reference to overriding hashcode() just talks about Collections. TY for the ref. – killjoy Nov 02 '18 at 00:14
2

It depends on the collection, most collections should work even if the hashCode of the elements has not been overridden, except collections like HashSet which rely on the element hashCode in order to work properly. Beware that the hashCode of a collection usually relies on the hashCode of the elements:

Returns the hash code value for this collection. While the Collection interface adds no stipulations to the general contract for the Object.hashCode method, programmers should take note that any class that overrides the Object.equals method must also override the Object.hashCode method in order to satisfy the general contract for the Object.hashCode method. In particular, c1.equals(c2) implies that c1.hashCode()==c2.hashCode()

See: http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html#hashCode%28%29

Christophe Roussy
  • 16,299
  • 4
  • 85
  • 85
0
**type of field**             **hash code formula**

boolean                       fieldHash = f ? 0 : 1

any integer type except long  fieldHash = (int) f

long                          fieldHash = (int) (f ^ (f >>> 32))

float                         fieldHash = Float.floatToIntBits( f )

double                        int v=Double.doubleToLongBits(f)

fieldHash                     (int) (v ^ (v >>> 32))

any Object reference          fieldHash = f.hashCode()

If you write a custom type you are responsible for creating a good hashCode implementation that will best represent the state of the current instance.

http://content.hccfl.edu/pollock/AJava/HashCode.htm

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Massimiliano Peluso
  • 26,379
  • 6
  • 61
  • 70