为什么java.util.Set没有get(int index)? [英] Why doesn't java.util.Set have get(int index)?

查看:562
本文介绍了为什么java.util.Set没有get(int index)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确定有一个很好的理由,但有人可以解释为什么 java.util.Set 接口缺少 get(int Index) ,或任何类似的 get()方法?





如果我知道我想要第一个项目,我可以使用 set.iterator()。next(),但是否则看起来我必须强制转换为Array才能在特定索引中检索项目。



从集合中检索数据的适当方法是什么? (除了使用迭代器)



我确定它被排除在API之外意味着有一个很好的理由不这样做 - 有人可以启迪我?



编辑:
这里有一些非常好的答案,还有几个说更多上下文。具体情况是一个dbUnit测试,其中我可以合理地断言从查询返回的集合只有一个项目,我正试图访问该项目。



但是,这个问题在没有场景的情况下更有效,因为它仍然更加集中:




解决方案

由于集没有排序。一些实现(特别是那些实现 java.util.SortedSet 接口),但是这不是集合的一般属性。



如果您尝试以这种方式使用集合,则应考虑使用列表。


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 scenario was 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.

However, the question is more valid without the scenario, as it remains more focussed:

What's the difference between set and list.

Thanks to all for the fantastic answers below.

解决方案

Because sets have no ordering. Some implementations do (particularly those implementing the java.util.SortedSet interface), but that is not a general property of sets.

If you're trying to use sets this way, you should consider using a list instead.

这篇关于为什么java.util.Set没有get(int index)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆