java Collections.singleton() 返回一个集合而不是一个集合有什么好处?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31599467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 18:50:52  来源:igfitidea点击:

What is the benefit for Collections.singleton() to return a Set instead of a Collection?

javacollections

提问by fge

The Collections.singleton()methodreturns a Setwith that single argument instead of a Collection.

Collections.singleton()方法返回Set带有该单个参数的 a 而不是 a Collection

Why is that so? From what I can see, apart from Setbeing a subtype of Collection, I can see no advantage... Is this only because Setextends Collectionanyway so there is no reason not to?

为什么呢?据我所知,除了Set作为 的子类型之外Collection,我看不出任何优势......这仅仅是因为无论如何都Set扩展Collection了所以没有理由不这样做吗?

And yes, there is also Collections.singletonList()but this is another matter since you can access random elements from a Listwith .get()...

是的,还有Collections.singletonList()但这是另一回事,因为您可以从Listwith .get()...

采纳答案by Louis Wasserman

I'm not sure there's a "benefit" or "advantage" per se? It's just the method that returns a singleton Set, and happens to be the default implementation when you want a singleton Collectionas well, since a singleton Collectionhappens to be a mathematical set as well.

我不确定本身是否有“好处”或“优势”?它只是返回单例的方法Set,并且当您也需要单例时恰好是默认实现Collection,因为单例Collection恰好也是一个数学集。

回答by Basil Bourque

Immutable

不可变

The benefit is found in the first adjective read in that JavaDoc documentation: immutable.

JavaDoc 文档中阅读的第一个形容词中可以找到好处:不可变

There are times when you are working with code that demands a Set(or List, etc.). In your own context you may have a strict need for only a single item. To accomplish your own goal of enforcing the rule of single-item-only while needing to present that item in a set, use a Setimplementation that forbids you from adding more than one item.

有时,您正在处理需要 a Set(或List等)的代码。在您自己的上下文中,您可能只需要一个项目。要实现您自己的目标,即在需要在集合中呈现该项目的同时强制执行仅单个项目的规则,请使用Set禁止添加多个项目的实现。

“Immutable” on Collections::singletonmeans that, once created, the resulting Setobject is guaranteed to have one, and only one item. Not zero, and not more than one. No more can be added. The one item cannot be removed.

“不可变”开启Collections::singleton意味着,一旦创建,生成的Set对象保证只有一项,而且只有一项。不为零,也不超过一。不能再添加了。不能删除一项。

For example, imagine your code is working with an Employeeobject representing the CEO (Chief Executive Officer) of your company. Your code is explicitly dealing with the CEO only, so you know there can be only one such Employeeobject at a time, always one CEO exactly. Yet you want to leverage some existing code that creates a report for a specified collection of Employeeobjects. By using Collection.singletonyou are guaranteed that your own code does not mistakenly have other than one single employee, while still being able to pass a Set.

例如,假设您的代码正在处理Employee代表您公司的 CEO(首席执行官)的对象。您的代码明确地仅与 CEO 打交道,因此您知道一次只能有一个这样的Employee对象,并且始终只有一位 CEO。然而,您希望利用一些现有代码为指定的Employee对象集合创建报告。通过使用,Collection.singleton您可以保证您自己的代码不会错误地包含一名员工,同时仍然能够通过Set.

Set< Employee > ceo = Collections.singleton( new Employee( "Tim Cook" ) ) ;  // Always exactly one item in this context, only one CEO is possible.

ceo.add( … ) ;     // Fails, as the collection is immutable.
ceo.clear() ;      // Fails, as the collection is immutable.
ceo.remove( … ) ;  // Fails, as the collection is immutable.

someReport.processEmployees( ceo ) ;

Java 9: Set.of& List.of

Java 9: Set.of&List.of

Java 9 and later offers new interface methods Set.ofand List.ofto th same effect, an immutable collection of a single element.

Java 9 和更高版本提供了新的接口方法Set.ofList.of相同的效果,单个元素的不可变集合。

Set< Pet > pet = Set.of( someDog ) ;

But sibling ofmethods are overloaded to accept any number of elements to be in the immutable collection, not just one element.

但是兄弟of方法被重载以接受不可变集合中的任意数量的元素,而不仅仅是一个元素。

Set< Pet > pets = Set.of( someDog , someOtherDog , someCat ) ;

回答by ordonezalex

I wondered the same thing and came across your question in my research. Here is my conclusion:

我想知道同样的事情,并在我的研究中遇到了你的问题。这是我的结论:

Returning a Setkeeps the Collections API clean.

返回 aSet可以保持 Collections API 干净。

Here are the methods for getting a singleton Collection:

以下是获取单例集合的方法:

  • public static <T> Set<T> singleton(T o)
  • public static <T> List<T> singletonList(T o)
  • public static <K,V> Map<K,V> singletonMap(K key, V value)
  • public static <T> Set<T> singleton(T o)
  • public static <T> List<T> singletonList(T o)
  • public static <K,V> Map<K,V> singletonMap(K key, V value)

What if the API designers decided on having a singletonSetmethod and singletonmethod? It would look like this:

如果 API 设计者决定拥有一个singletonSet方法和singleton方法怎么办?它看起来像这样:

  • public static <T> Collection<T> singleton(T o)
  • public static <T> Set<T> singletonSet(T o)
  • public static <T> List<T> singletonList(T o)
  • public static <K,V> Map<K,V> singletonMap(K key, V value)
  • public static <T> Collection<T> singleton(T o)
  • public static <T> Set<T> singletonSet(T o)
  • public static <T> List<T> singletonList(T o)
  • public static <K,V> Map<K,V> singletonMap(K key, V value)

Is the singletonmethod really necessary? Let's think about why we would need some of these methods.

singleton真的有必要方法?让我们想想为什么我们需要其中一些方法。

Think about when you would call singletonList? You probably have an API that requires Listinstead of Collectionor Set. I will use this poor example:

想想你什么时候会打电话singletonList?您可能有一个需要List而不是Collection或的 API Set。我将使用这个糟糕的例子:

public void needsList(List<?> list);

You can only pass a List. needsListhopefully needs the data indexed and is not arbitrarily requesting a Listinstead of a Collection.

您只能通过一个List. needsList希望需要索引的数据,而不是随意请求 aList而不是 a Collection

However, you could also pass a Listto a method that required any Collection:

但是,您也可以将 a 传递List给需要 any 的方法Collection

public void needsAnyCollection(Collection<?> collection);

But if that is the case, then why use a List? A Listhas a more complicated API and involves storing indexes. Do you really need the indexes? Would a Setnot suffice? I argue that you should use a Set, because needsAnyCollectiondoes not care about the order.

但如果是这样,那为什么要使用 a List?AList有一个更复杂的 API,涉及存储索引。你真的需要索引吗?将一个Set还不够?我认为你应该使用 a Set,因为needsAnyCollection不关心顺序。

This is where singletonSetreally shines. You know that if the collection is of size 1 (singleton), then the data must be unique. Collections of size 1 are coincidentally a Set.

这才是singletonSet真正闪耀的地方。您知道如果集合的大小为 1(单例),则数据必须是唯一的。大小为 1 的集合恰好是一个集合。

There is no need for a method which returns a singleton of type Collection, because it is accidentally a Set.

不需要返回类型为单例的方法Collection,因为它意外地是Set.

回答by Alex

The reason singleton Collections exist is to provide a low memory collection if you know you are going to store 1 element and it is not going to be mutated. Especially in high volume services this can have significant impact due to garbage collection latency.

单例集合存在的原因是如果您知道要存储 1 个元素并且它不会发生变异,则提供低内存集合。特别是在大容量服务中,由于垃圾收集延迟,这可能会产生重大影响。

This applies for both Set.of("1");and Collections.singleton("1");

这适用于Set.of("1");Collections.singleton("1");

Since Setis a Collectionalready returning the more constrained contract is a good thing for users of the libraries. You get additional functionality without paying anything for it.

既然Set是一个Collection已经返回了更多的限制合同是图书馆的用户是一件好事。您无需支付任何费用即可获得额外的功能。

And you as a user should do the same as for any other API and library, you should store the least needed contract for it.

作为用户,您应该对任何其他 API 和库执行相同的操作,您应该为其存储最不需要的合约。

So if the only thing you'll ever need to do with the structure is to iterate in a loop I'd suggest to choose Iterableinstead of using List, Setor Collection. Since aCollectionis an Iterablethis will work out of the box.

因此,如果您唯一需要对结构做的事情就是在循环中进行迭代,我建议您选择Iterable而不是使用List,SetCollection。由于 aCollection是 anIterable这将是开箱即用的。

回答by Dici

Not all the lists are random access, just take a LinkedList(random access in the API, not in the implementation)as a counter-example. By the way I agree with Louis Wasserman, a Setsimply makes sense because it is closer to the mathematical definition, it just feels natural.

并不是所有的列表都是随机访问的,就拿一个LinkedList(API中的随机访问,而不是实现中的)作为反例。顺便说一下,我同意 Louis Wasserman 的Set观点, a很有意义,因为它更接近数学定义,感觉很自然。