Why doesn't java.util.Set have get(int index)?

前端 未结 18 1293
长情又很酷
长情又很酷 2020-11-28 18:14

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()

18条回答
  •  -上瘾入骨i
    2020-11-28 19:00

    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.

提交回复
热议问题