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

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

问题描述

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

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.

如果我知道我想要第一个项目,我可以使用 set.iterator().next(),但否则我似乎必须转换为一个数组来检索特定位置的项目索引?

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)

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

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?

这里有一些非常好的答案,还有一些说更多上下文".特定场景是 dbUnit 测试,我可以合理地断言从查询返回的集合只有 1 个项目,并且我正在尝试访问该项目.

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:

集合和列表有什么区别.

感谢大家在下面的精彩回答.

Thanks to all for the fantastic answers below.

推荐答案

因为集合没有顺序.一些实现可以(尤其是那些实现 java.util.SortedSet 接口的实现),但这不是集合的一般属性.

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天全站免登陆