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

Posted by Marty Pitt on Stack Overflow See other posts from Stack Overflow or by Marty Pitt
Published on 2009-04-20T19:19:40Z Indexed on 2010/05/30 1:02 UTC
Read the original article Hit count: 272

Filed under:
|
|
|

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

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 sure the fact that it's excluded from the API means there's a good reason for not doing this -- could someone please enlighten me?

EDIT: Some extremely great answers here, and a few saying "more context". The specific scneario was a dbUnit test, where I could reasonalby assert that the returned set from a query had only 1 item, and I was trying to access that item.

However, the question is more valid without the scenario, as it remains more focussed : What's the difference between set & list.

Thanks to all for the fantastic answers below.

© Stack Overflow or respective owner

Related posts about java

Related posts about data-structures