Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't SingletonSet implement SortedSet

In order so reduce memory consumption, I'm rewriting a class that has a SortedSet<Integer>. In 80% of cases, this collection contains only a single element . So I thought I could use a SingeltonSet in these cases and a normal TreeSet in other cases. Now I noticed that SingletonSet, as returned by Collections.singleton(), does not implement SortedSet. Is there any reason for this shortcoming? A single element can always be considered sorted I'd say. Do I have to write my own SingletonSet implementation?

like image 317
steffen Avatar asked Jun 06 '17 20:06

steffen


1 Answers

The SortedSet interface defines methods that require a Comparator for the set elements. Thus elements maintained by a SortedSet have to be comparable. If the singleton returned by Collections.singleton() would implement SortedSet, then Collections.singleton() could accept Comparables only (which is not what we want).

like image 90
steffen Avatar answered Oct 06 '22 05:10

steffen