No ListIterator in LinkedHashMap and LinkedHashSet
Asked Answered
W

2

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?

Whorish answered 9/10, 2014 at 11:17 Comment(0)
D
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.

Deplorable answered 9/10, 2014 at 11:37 Comment(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.Whorish
No. LinkedList allows to insert at specified positions.Deplorable
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.Whorish
P
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...

Picket answered 9/10, 2014 at 11:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.