3

Although the documentation specifically states that both LinkedHashMap and LinkedHashSet

maintains a doubly-linked list running through all of its entries

I don't understand why these implementations do not return a ListIterator to navigate with next and previous. Is anyone aware of the limitations under the hood?

asked Oct 9, 2014 at 11:17

2 Answers 2

5

A ListIterator opens the possibility of inserting through them "at the current position of the iterator". But that breaks the ordering imposed by the LinkedHashMap/Set itself because their contract says that the list order will be strictly equal to the insertion order.

answered Oct 9, 2014 at 11:37
3
  • Sounds reasonable, what's confusing is that a LinkedList do return a ListIterator. Similar to the structures I am mentioning, a LinkedList is double-linked and is supposed to maintain the original insertion order. Commented Oct 10, 2014 at 8:43
  • No. LinkedList allows to insert at specified positions. Commented Oct 10, 2014 at 12:19
  • I see, because it implements the List interface, while the LinkedHashMap/Set don't. Then, the double linking is useful when getting the reverse iterator. Commented Oct 10, 2014 at 15:19
0

You cannot iterate directly through a data structure of key/value pairs, which is not a collection. Even if, internally, there is a doubly-linked list that remembers the insertion order, you still have to get the iterator the standard way.

There are methods on those data structures that return collections of keys, values, or entries (key+value): keySet(), values(), entrySet(), which you can get iterators from.

Maybe what you want is map.entrySet().iterator() here, though I agree this is a set, and the order is technically unspecified...

answered Oct 9, 2014 at 11:23

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.