Menu

1 / 2

Hash Collision in Java

DEV Community·Tapas Pal·6 months ago
#txPZJwZV
#hashmap#java#career#programming#hashcode
Reading 0:00
15s threshold

Mutable Key Problem in HashMap

HashMap depends on hashCode() remaining stable

If the key changes after insertion:

hashCode changes

bucket location changes

HashMap cannot find the object anymore

First Understand One Critical Rule

HashMap Stores Entry Based On: hashCode() + equals()

Simple Mutable Key Example

Employee Class

class Employee { String name ; Employee ( String name ) { this . name = name ; } @Override public int hashCode () { return name . hashCode (); } @Override public boolean equals ( Object obj ) { Employee e = ( Employee ) obj ; return this . name . equals ( e . name ); } }

Enter fullscreen mode

Exit fullscreen mode

Step 1 — Create Object

Employee emp = new Employee ( "John" );

Enter fullscreen mode

Exit fullscreen mode

Current value:

name = "John"

Step 2 — Put into HashMap

Map < Employee , String > map = new HashMap <>(); map . put ( emp , "Developer" );

Enter fullscreen mode

Exit fullscreen mode

What Happens Internally?

A.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.