views:

180

answers:

3

When LinkedHashMap.keySet() is called, will the order of the Set returned be the same as the order the keys were added in?

A: 

A set is always unordered, so the answer is no.

tob
The `Set` interface doesn't guarantee order
Noel M
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
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
+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
@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
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
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
@Tom I didn't mention `SortedSet` and there could be an implementation of Set which implied order other than natural order.
Alison
@Alison: I mentioned `SortedSet` because what is a subclass of `Set` with a fixed ordering other than a `SortedSet`?
Tom Tresansky
@Tom `LinkedHashSet`? This might seem a more logical assumption in this case.
Alison
But `LinkedHashSet` does not implement `SortedSet'.
Tom Tresansky
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
+1 Good catch on that corner case.
Tom Tresansky
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