What happens if hashCode() method is not overridden?

why hashcode is important?

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.
Example :
MyObject a = new MyObject(“a”, 123,”something”);
MyObject b = new MyObject(“a”, 123,”something”);
a and b will have different hash codes.
According equals() and hashCode() contract, if two objects are equal by equals() method then they must return same hash Code.




Java Learner

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

What did you think about Drop The Number® : Merge Game Cheats&Hack

LBank to Launch BCK Demand Deposit and Fixed Deposit

2 easy techniques to create powerful GIFs

Dungeon Evolver: nuts & bolts

Why won’t my SQLAlchemy frontend connect to my PostgreSQL backend?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sudheer Kumar

Sudheer Kumar

Java Learner

More from Medium

What to Look for When Hiring a Java Developer

The Art Of Programming #10

Reversing a String and Checking Whether It’s a Palindrome

Java coding for kids.