I\'m sure there\'s a good reason, but could someone please explain why the java.util.Set
interface lacks get(int Index)
, or any similar get()
I ran into situations where I actually wanted a SortedSet with access via index (I concur with other posters that accessing an unsorted Set with an index makes no sense). An example would be a tree where I wanted the children to be sorted and duplicate children were not allowed.
I needed the access via index to display them and the set attributes came in handy to efficiently eliminate duplicates.
Finding no suitable collection in java.util or google collections, I found it straightforward to implement it myself. The basic idea is to wrap a SortedSet and create a List when access via index is required (and forget the list when the SortedSet is changed). This does of course only work efficiently when changing the wrapped SortedSet and accessing the list is separated in the lifetime of the Collection. Otherwise it behaves like a list which is sorted often, i.e. too slow.
With large numbers of children, this improved performance a lot over a list I kept sorted via Collections.sort.