4

Lately,I've been going through implementations of Map interface in java. I understood HashMap and everything made sense. But when it comes to LinkedHashMap, as per my knowledge so far, the Entry has key, value, before and after. where before and after keeps track of order of insertion.

However, using hashcode and bucket concept doesn't make sense to me in LinkedHashMaps.

I went through this article for understanding implementation of linkedHashMaps

Could someone please explain it? I mean why does it matter in which bucket we put the entry node. In fact why bucket concept in the first place.? why not plain doubly llinked lists?

Arun Gowda
  • 2,721
  • 5
  • 29
  • 50

1 Answers1

6

LinkedHashMap is still a type of a HashMap. It uses the same logic as HashMap in order to find the bucket where a key belongs (used in methods such as get(),put(),containsKey(),etc...). The hashCode() is used to locate that bucket. This logic is essential for the expected O(1) performance of these operations.

The added functionality of LinkedHashMap (which uses the before and after references) is only used to iterate the entries according to insertion order, so it affects the iterators of the Collections returned by the keySet(),entrySet() & values() methods. It doesn't affect where the entries are stored.

Without hashcodes and buckets, LinkedHashMap won't be able to lookup keys in the Map in O(1) expected time.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Do you mean everything in `LinkedHashMap` (like `get(),put(),contains()`) is same as `HashMap` ,except for traversal/iteration it uses before and after? – Arun Gowda Feb 22 '18 at 07:19
  • 2
    @ArunGowdru yes. Though methods such as `put()` and `remove()` also have some differences in LinkedHashMap - they contain additional logic to update the values of the `before` and `after` references. – Eran Feb 22 '18 at 07:26
  • 2
    @ArunGowdru In Java 8, `LinkedHashMap` doesn’t even override the `put` or `contains` methods but just uses the inherited methods. This works because `HashMap` has been designed to be extendable for `LinkedHashMap`, i.e. all nodes are created via [(package-private) overridable factory methods](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/HashMap.java#1724) and it also invokes [dedicated callback methods](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/HashMap.java#1764). – Holger Feb 22 '18 at 08:21