-3

I Want to know how to retrieve Linked list of a particular bucket in hash-map.

We know that key is stored in buckets and each bucket has a Linked-list if collision of key occurs. So if Hash map is maintaining linked-list not removing or overwriting values So how can we retrieve that linked list?

2 Answers2

1

So how can we retrieve that linked list?

I am afraid that you can't. And for a number of reasons. For example:

  1. It is an implementation detail that is hidden because it is subject to change without notice.

  2. It is actually not a linked list in recent implementations (Java 8 onwards) ... which reinforces the message of the first point. Yes, they did change it.

  3. If you were able to access the data structure directly, your code would be liable to break in "interesting ways" due to changes unexpected changes made to the structures via normal operations in the HashMap API.`

  4. Your code could also break the data structures in "interesting ways".


Now if you were a bit crazy, you could ignore the above rationale and use reflection to break abstraction and access the data structures. But please don't try this in any project I have anything to do with!

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

Actually, you can't assume HashMap use linked lists. OpenJDK8's HashMap is a mixture of linked lists and trees.

It is a private variable, so you need to use reflection and rely on the internal detail. But once you go that path, you create dependency to that specific JDK version. For example, if you implement code to traverse the JDK8 HashMap, it may become useless with JDK9 tree, and so on, let alone other JDK implementation. (Edit: Looks like reflection may not work with Java 9.)

If you want to rely on some particular HashMap implementation, you should as well implement it yourself (or copy the OpenJDK one).

snipsnipsnip
  • 2,268
  • 2
  • 33
  • 34