以自然顺序将唯一元素存储在集合中 [英] To store unique element in a collection with natural order

查看:168
本文介绍了以自然顺序将唯一元素存储在集合中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解决Java测试时,遇到了以下问题:

While I was solving a Java test I came up with the following question:


您需要将元素存储在保证不会存储任何
重复项,并且可以按自然的
顺序访问所有元素。哪个接口提供了该功能?

You need to store elements in a collection that guarantees that no duplicates are stored and all elements can be accessed in natural order. Which interface provides that capability?



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 实现(即 TreeMap (由文档说明),那么您可以保证顺序自然且没有重复的条目。

  • 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 一样, TreeSet 是一个集合,可用于以自然顺序存储事物,没有重复项。

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.

    这篇关于以自然顺序将唯一元素存储在集合中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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