views:

59

answers:

3

Does the entrySet() function that is called from a treemap instance return a TreeSet of entry's or simply a set of entry's.Is the order ensured?

Instead of getting it as a set of entry's how can a get a list of entry's in order?

+1  A: 

From the JavaDoc:

public Set<Map.Entry<K,V>> entrySet()

Returns a Set view of the mappings contained in this map. The set's iterator returns the entries in ascending key order.

Thomas Lötzer
Which does not makes it a TreeSet, but rather (and I cannot consider that for granted) a SortedSet.
Riduidel
Right, its definetly a sorted set, but not necessarily a `java.util.SortedSet` or even a TreeSet.
Thomas Lötzer
+1  A: 

It's the other way around: a TreeSet uses a TreeMap internally. (See first sentence of the TreeSet docs)

There's not much Sun java source code I can find on the web to link to, but here are some oldish versions:

As you can see, TreeMap defines an inner class called TreeMap.EntrySet which just extends AbstractSet. And no, it does not implement SortedSet (which would otherwise probably be specified by the SortedMap.entrySet() contract).

But to answer the actual question: yes, the order is ensured as specified in the SortedMap.entrySet() contract.

seanizer
+1  A: 
Assert.assertFalse(new TreeMap().keySet() instanceof SortedSet );
Assert.assertFalse(new TreeMap().keySet() instanceof TreeSet ); //no need to assert

But the set has order actually.

卢声远 Shengyuan Lu