问题描述
我正在解决Java测试时,遇到了以下问题:
While I was solving a Java test I came up with the following question:
A. java.util.Map
B. java.util.Set
C. java.util.List
D. java.util.Collection
我不知道这里合适的情况是什么?我们可以在所有这些集合中存储相同的元素,除非存储在 Set
中,但是 Set
不提供自然秩序。
I have no idea what is the right case here? We can store the same element in any of these collections unless in a Set
, but the Set
doesn't provide the natural order. What's wrong?
推荐答案
该测试的正确答案是 Set
让我们记住,它正在请求一个可以提供此功能的接口;给定正确的实施方式, Set
接口可以提供该功能。
The correct answer for that test is Set
Let's remember that it's asking for an interface that could provide that; given the right implementation, the Set
interface could provide it.
-
Map
接口不对事物的存储顺序做出任何保证,因为这是实现特定的。但是,如果您使用 right 实现(即(由文档说明),那么您可以保证顺序自然且没有重复的条目。
The
Map
interface doesn't make any guarantees around what order things are stored, as that's implementation specific. However, if you use the right implementation (that is,TreeMap
as spelled out by the docs), then you're guaranteed a natural ordering and no duplicate entries.
但是,不需要键值对。
Set
接口也不保证事物存储的顺序,因为这是实现特定的。但是,像 TreeMap
一样,是一个集合,可用于以自然顺序存储事物,没有重复项。
The Set
interface also doesn't make any guarantees around what order things are stored in, as that's implementation specific. But, like TreeMap
, TreeSet
is a set that can be used to store things in a natural order with no duplicates.
这是它的外观。
Set<String> values = new TreeSet<>();
列表
界面肯定会
Collection
接口没有任何直接实现,但这是整个集合层次结构的先祖。因此,从理论上讲,这样的代码是合法的:
The Collection
interface doesn't have anything directly implementing it, but it is the patriarch of the entire collections hierarchy. So, in theory, code like this is legal:
Collection<String> values = new TreeSet<>();
...但是您会丢失有关其实际类型的信息,所以我d不鼓励使用。
...but you'd lose information about what kind of collection it actually was, so I'd discourage its usage.
这篇关于以自然顺序将唯一元素存储在集合中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!