Reputation: 1433
Java docs says that a "TreeSet keeps its elements ordered internally".
Here what does ordering mean? Does it mean sorted? If so, then what is the difference between sorting and ordering?
Upvotes: 0
Views: 1144
Reputation: 262644
"Ordered" means that there is a defined order in which the elements can be retrieved. This means that when you iterate over the Collection, you know in which order you will get the elements.
In this case it does mean "sorted" (because the TreeSet arranges elements according to a given Comparator, i.e. it sorts them).
In other cases (such as a Queue), it can mean "insertion order".
In the case of a List, you can specify the order yourself (by assigning each element an index), and the List will keep them in this order (which is independent of insertion order or any sort order).
Contrast this to a HashSet, which makes no guarantees about the order of elements when retrieved.
Upvotes: 1
Reputation: 79981
The ordering in TreeSet
, from the Javadoc:
A NavigableSet implementation based on a
TreeMap
. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.
Here "natural ordering" means the class can implement Interface Comparable, which allows you to specify the behavior of compareTo()
.
You can also use the TreeSet
constructor that allows you specify a Comparator
class that will dictate the type of ordering: http://docs.oracle.com/javase/6/docs/api/java/util/TreeSet.html#TreeSet(java.util.Comparator)
Upvotes: 1
Reputation: 26512
Yes. It is sorted using the natural sort order of the type of its elements (e.g. alphabetical order for strings, numerical order for ints, etc), unless a comparator is provided to define sort order.
The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.
From the TreeSet Javadoc.
Upvotes: 1