3

Does anyone use hashCode() anywhere?

Can anyone give me an example of the exact use of hashcode and in which cases we need to implement it? Any specific area where HashCode is being used?

Matthew Farwell
  • 60,889
  • 18
  • 128
  • 171
Ketan Bhavsar
  • 5,338
  • 9
  • 38
  • 69

3 Answers3

10

Does hascode use any where?

The hashCode method is used internally by for instance HashSet or HashMap etc.

Do any one give me example what is exact use of hascode ...

It is used to for instance allow an algorithm to quickly discover if two objects are not equal. (Without comparing them using equals.)

...and in which cases we need to implement it?

You should implement it whenever you override equals (which you need to do whenever you need to define two different objects to be equal).


Further reading

Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
2

hashCode is used for example in the hashmap. a good implementation of the method hashMap permits to have a good data distribution in the map and improve data access performances

Ste
  • 141
  • 1
  • 8
2

I think you mean hashcode, not hascode...

That being said, the hashcode is used to construct structures such as Maps (HashMap, etc).

It is also used to store passwords sometimes, so basically the Java application will pass the database a hashed version of the password which is then stored. This is useful when you have 'leaks' between the Java application and the database, which allow people to see the usernames and their passwords. Since you will be passing a hashed version of the password rather than the actual password, whoever is spying on your application will have a very hard time trying to crack the password.

To log in someone, all that the application needs to do is to compare the hash codes of the password provided and the one which is stored in the database.

npinti
  • 51,780
  • 5
  • 72
  • 96