Tuesday, May 6, 2014

What does the hashCode() method do?

hashCode() is a public method present in the Object class that returns an int value.

When we invoke a hashCode() method on an object, it calculates an int value based on the object contents and returns the calculated value.

So where this hashCode is used?
     Say we  have a Book class.


class Book{
String name ;
int bookid;
public Book(String name) {
this.name=name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getBookid() {
return bookid;
}
public void setBookid(int bookid) {
this.bookid = bookid;
}

}

Now we are creating a Hashtable of books.

Book book1=  new Book("Java");
book1.setBookid(1);
Book book2=  new Book("C++");
book2.setBookid(2);

Hashtable<Integer, Book> ht = new Hashtable<Integer, Book>();
ht.put(book1.getBookid(),book1);
ht.put(book2.getBookid,book2);

So now Hash table will have two elements book1 and book2. When we are storing the book objects internally the key [1] is used in the hashCode() method to calculate a hashcode and that value is stored in the memory against the value.

So when we try to get an object from hashtable,
ht.get(1);

it will return book1 object. Now again internally it calculates the hashcode for the key [1] and searches the hashtable with the hashcode  as the key and retrieves the value.







No comments:

Post a Comment