Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is no Hashable interface in Java

Tags:

Object in Java has hashCode method, however, it is being used only in associative containers like HashSet or HashMap. Why was it designed like that? Hashable interface having hashCode method looks as much more elegant solution.

like image 573
karlicoss Avatar asked Aug 26 '12 18:08

karlicoss


People also ask

How hash table is implemented in Java?

The Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method. It is similar to HashMap, but is synchronized.

How hashCode works in Java internally?

Simply put, hashCode() returns an integer value, generated by a hashing algorithm. Objects that are equal (according to their equals()) must return the same hash code. Different objects do not need to return different hash codes.

Why hashCode is used in Java?

HashMap and HashSet use hashing to manipulate data. They use hashCode() method to check hash values. The default implementation of hashCode() in Object class returns distinct integers for different objects.


1 Answers

The major argument seems to me that there is a well-defined default hashCode that can be calculated for any Java object, along with an equally well-defined equals. There is simply no good reason to withhold this function from all objects, and of course there are plenty reasons not to withhold it. So it's a no-brainer in my book.

like image 181
Marko Topolnik Avatar answered Sep 20 '22 20:09

Marko Topolnik