I have the following code snippet:
class Cert {
public static void main(String[] args) throws IOException {
NavigableSet<Integer> navigableSet = new TreeSet<Integer>();
List a = new ArrayList<Integer>();
a.add(1);
a.add(2);
a.add(-1);
navigableSet.addAll(a);
Iterator< Integer> iterator = navigableSet.descendingSet().headSet(1).iterator();
while (iterator.hasNext())
{
System.out.print(iterator.next() + " ");
}
}
}
This code returns “2”. But here’s what the official javadoc (Java 6) for headSet says:
SortedSet headSet(E toElement)
Returns a view of the portion of this set whose elements are strictly less than toElement. The returned set is backed by this set, so changes in the returned set are reflected in this set, and vice-versa. The returned set supports all optional set operations that this set supports.
According to the above, the program should print only “-1”. Did the javadoc forget the descending case?
Thanks in advance
The javadoc fragment you quoted would have been more precise if it referred to generic comparison rather than explicitly say less than. This case is described in
descendingSet()‘s documentation: