Alex Rivera | Logout

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

Asked 2009-04-20T19:19:40.460
248

Why does the java.util.Set interface lack get(int Index), or any similar get() method?

It seems that sets are great for putting things into, but I can't find an elegant way of retrieving a single item from them.

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)

I'm asking this question because I had a dbUnit test, where I could reasonably assert that the returned set from a query had only 1 item, and I was trying to access that item.

So, what's the difference between Set and List?

Edit
Report

1 Answer

3

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.

answered 2010-08-18T13:33:43.910

Your Answer