Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For HashMap, should I override hashCode for key or value?

Does HashMap use the hashCode and equals methods of the key or value to store its entries, i.e., which is the class whose hashCode and equals methods we need to override? Should it be the key's class (K), or the value's class (V)?

like image 546
Diego Ramos Avatar asked Sep 02 '25 09:09

Diego Ramos


1 Answers

The value is essentially irrelevant to the Map itself: it's only the key which is considered by the HashMap when it is deciding where to put the key/value pair within its internal data structure.

However, you might want to override it for the value too, e.g. if you need to do map.values().contains(...).

like image 80
Andy Turner Avatar answered Sep 05 '25 00:09

Andy Turner