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()
Just adding one point that was not mentioned in mmyers' answer.
If I know I want the first item, I can use set.iterator().next(), but otherwise it seems I have to cast to an Array to retrieve an item at a specific index?
What are the appropriate ways of retrieving data from a set? (other than using an iterator)
You should also familiarise yourself with the SortedSet interface (whose most common implementation is TreeSet).
A SortedSet is a Set (i.e. elements are unique) that is kept ordered by the natural ordering of the elements or using some Comparator
. You can easily access the first and last items using first()
and last()
methods. A SortedSet
comes in handy every once in a while, when you need to keep your collection both duplicate-free and ordered in a certain way.
Edit: If you need a Set whose elements are kept in insertion-order (much like a List), take a look at LinkedHashSet.