Home Sets and maps
Sets, maps, and ordering
When working with sets, recall that the
Set interface does not guarantee the
items will be ordered in any particular way. That means that if you are trying to get an
item at a certain "index" or get the "first" item in a set (whether it's a
TreeSet or a
HashMap, you are doing something wrong and should
restructure your code.
The same kind of logic also applies for keys in maps.
Unlike lists, there is no notion of "ordering" with
Maps. That means the only ways you can get "information" from a
Set is by:
- Checking to see if some item is a member of a set or is a key within a map
- Iterating over the entire set or the entire keyset of a map.
More precisely, the only ways to get "information" is by performing a membership check or by iteration.
While it is possible to write (somewhat ugly) code that does grab whatever happens to be selected "first" when iterating, you should not do so. Since sets are not guaranteed to be ordered in any way, the notion of there even existing a "first" item is dubious to begin with.