I know LinkedHashMap
has a predictable iteration order (insertion order). Does the Set
returned by LinkedHashMap.keySet()
and the Collection
returned by LinkedHashMap.values()
also maintain this order?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Don't get confused with
LinkedHashMap.keySet()
andLinkedHashMap.entrySet()
returning Set and hence it should not guarantee ordering !Set
is an interface withHashSet
,TreeSet
etc beings its implementations. TheHashSet
implementation ofSet
interface does not guarantees ordering. ButTreeSet
does. AlsoLinkedHashSet
does.Therefore it depends on how
Set
has been implemented inLinkedHashMap
to know whether the returning Set reference will guarantee ordering or not. I went through the source code ofLinkedHashMap
, it looks like this:Thus LinkedHashMap/HashMap has its own implementation of
Set
i.e.KeySet
. Thus don't confuse this withHashSet
.Also, the order is maintained by how the elements are inserted into the bucket. Look at the
addEntry(..)
method ofLinkedHashMap
and compare it with that ofHashMap
which highlights the main difference betweenHashMap
andLinkedHashMap
.I don't think you can presume the ordering of keySet() and values().
I can easily write an implementation of LinkedHashMap that returns you unordered keySet() and values(), as long as I stick to the contract of these two methods that are defined in Map, and overridden in HashMap.
You can assume so. The Javadoc says 'predictable iteration order', and the only iterators available in a Map are those for the keySet(), entrySet(), and values().
So in the absence of any further qualification it is clearly intended to apply to all of those iterators.
Looking at the source, it looks like it does.
keySet()
,values()
, andentrySet()
all use the same entry iterator internally.-- Map
-- LinkedHashMap
So, yes,
keySet()
,values()
, andentrySet()
(the three collection views mentioned) return values in the order the internal linked list uses. And yes, the JavaDoc forMap
andLinkedHashMap
guarantee it.That is the point of this class, after all.
Looking at the interface it returns a plain
Set
and not anSortedSet
. So there are no guarantees.Before assuming an implicit guarantee by looking at the implementation (always a bad idea) also look at the implementations in all other Java implementations :)
You could better create for instance a TreeSet with the keySet in the constructor.