tags:

views:

150

answers:

5

If we implement our own keys in Hashtable, then our custom hashtable keys must implement

public int hashCode()
{
}

and

 public Object equals(Object obj)
   {
   }

What will be the implementations for these methods?

+1  A: 

Read this article: http://www.ibm.com/developerworks/java/library/j-jtp05273.html

drvdijk
+3  A: 

Read "Effective Java 2nd Edition", this is a good time for it.

HashCode and Equals method in Java object – A pragmatic concept

Java Equals Implementation

Equals and Hashcode Implementation.

Adeel Ansari
thanks a lot for enlightening me
jezhilvalan
Have a look to the dfa's post. He provided the link to the exact chapter of Effective Java. My last two links are kinda old. FIrst one is good to go.
Adeel Ansari
+2  A: 

Effective Java 2nd edition has the best explaination for these two methods: check the gory deailt here.

dfa
+1  A: 

After you understood it by reading effective java, you might use commons lang EqualsBuilder and HashCodeBuilder to implement it. If the part isn't performance critical, you even can use the refelction method like this:

 public boolean equals(Object obj) {
   return EqualsBuilder.reflectionEquals(this, obj);
 }


public int hashCode() {
   return HashCodeBuilder.reflectionHashCode(this);
 }

It don't gets much easier :)

Tim Büthe
thanks a lot for enlightening me
jezhilvalan
I really like the EqualsBuilder and HashCodeBuilder classes, although I typically avoid the reflection methods because of the performance concerns.
harmanjd
@harmanjd: Yes, if it is performance critical, you should avoid it, but most of the time it isn't. If you use hibernate for example, it heavily relies on reflection to find differences between object before updating the database. If you do a 10 or 100 millis taking database operation afterwards, the 2 nanoseconds for comparing objects with reflection are just insignificant.
Tim Büthe
A: 

These methods are used for hashtable implementation to identify elements while inserting and retrieval.

  1. hashcode is the key for storing
  2. equals used methods contains, get etc to check the keys.
Krishna Kumar