When LinkedHashMap.keySet() is called, will the order of the Set returned be the same as the order the keys were added in?
The `Set` interface doesn't guarantee order
Noel M
2010-08-13 15:40:38
That's what I am saying. Regardless of any assumptions made by reading the documentation, a set is always unordered by definition so you cannot rely on an order.
tob
2010-08-13 16:47:43
What it *actually says* is 'The elements are returned in no particular order (unless this set is an instance of some class that provides a guarantee).' Such as LinkedHashMap.
EJP
2010-08-14 05:58:28
+3
A:
Yes.
See: LinkedHashMap:
This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).
and from the HashMap#keySet documentation:
The set [returned] is backed by the map, so changes to the map are reflected in the set, and vice-versa.
Tom Tresansky
2010-08-13 14:59:56
@Tom thanks, I'm still not convinced that this is explicit. Why wouldn't LinkedHashMap.keySet() return a subclass of Set with fixed ordering?
Alison
2010-08-16 09:39:03
Because if it returned a SortedSet, then LinkedHashMap would be adding the requirement that its keys are of a type which implements Comparable, or that a comparator function be supplied. This is NOT required by Map. Check out the SortedSet documentation: http://download.oracle.com/javase/6/docs/api/java/util/SortedSet.html. Not having this requirement allows even keys which do not implement Comparable to be used in a LinkedHashMap, which is the more general case. LinkedHashMap's implementation might even return a SortedSet if its keys ARE Comparable, but it simply isn't REQUIRED to.
Tom Tresansky
2010-08-16 17:56:54
Of course, the contract of LinkedHashMap says that it maintains INSERTION ordering, which may not be the NATURAL ordering. So in that case, a SortedSet wouldn't work at all---the keys simply wouldn't be sorted in that manner.
Tom Tresansky
2010-08-17 11:05:53
@Tom I didn't mention `SortedSet` and there could be an implementation of Set which implied order other than natural order.
Alison
2010-08-17 16:48:44
@Alison: I mentioned `SortedSet` because what is a subclass of `Set` with a fixed ordering other than a `SortedSet`?
Tom Tresansky
2010-08-31 18:56:24
@Tom `LinkedHashSet`? This might seem a more logical assumption in this case.
Alison
2010-09-01 09:13:40
A:
Yes. The exception is that when a key is reinserted, it appears in the order in which it was first inserted to the list.
relet
2010-08-13 15:03:17
Actually, the exception is for when the key is **reinserted**, not deleted and reused. The case is when you call `put(key, value)` for a key that was already in the map. (The javadoc explains this clearly.)
Stephen C
2010-08-13 15:26:43