何时使用设置与集合? [英] when to use Set vs. Collection?
问题描述
在Java中 Set
和 Collection
之间有任何实际差异,除了 Collection
可以包含同一个元素两次吗?它们有相同的方法。
Is there any practical difference between a Set
and Collection
in Java, besides the fact that a Collection
can include the same element twice? They have the same methods.
(例如,设置
给我更多的选项, code>设置 s但不是集合
s?)
(For example, does Set
give me more options to use libraries which accept Set
s but not Collection
s?)
编辑:我可以想到至少5种不同的情况来判断这个问题。任何人都可以想出更多?
edit: I can think of at least 5 different situations to judge this question. Can anyone else come up with more? I want to make sure I understand the subtleties here.
- 设计一个接受
参数的方法 code>或
Collection
。Collection
是更通用的,并接受更多的输入可能性。 (如果我正在设计一个特定的类或接口,如果我使用Collection
),我对我的消费者更好,对我的子类/实现者更严格。) 设计一个返回 - 设计一个实现接口
Set
或Collection
的类。与#2类似的问题。 c>设置一个扩展接口的接口设置
或Collection
。非常类似于#3。 - 编写使用
设置
或集合
的代码。这里我可以使用Set
;我使用Collection
的唯一原因是如果我从别人的代码中取回Collection
,或者如果我以处理包含重复项的集合。
Set
或 Collection
的方法。 设置
提供比 Collection
更多的保证(即使它只是保证不包括一个元素两次)。 (如果我设计一个特定的类或接口,如果我使用 Set
,我对我的消费者更好,对我的子类/实现者更严格。) - designing a method which accepts an argument of
Set
orCollection
.Collection
is more general and accepts more possibilities of input. (if I'm designing a specific class or interface, I'm being nicer to my consumers and stricter on my subclassers/implementers if I useCollection
.) - designing a method which returns a
Set
orCollection
.Set
offers more guarantees thanCollection
(even if it's just the guarantee not to include one element twice). (if I'm designing a specific class or interface, I'm being nicer to my consumers and stricter on my subclassers/implementers if I useSet
.) - designing a class that implements the interface
Set
orCollection
. Similar issues as #2. Users of my class/interface get more guarantees, subclassers/implementers have more responsibility. - designing an interface that extends the interface
Set
orCollection
. Very similar to #3. - writing code that uses a
Set
orCollection
. Here I might as well useSet
; the only reasons for me to useCollection
is if I get back aCollection
from someone else's code, or if I have to handle a collection that contains duplicates.
推荐答案
集合
也是列表
,队列
, Deque
所以它给你更多的选择。例如,我尝试使用 Collection
作为不应显式依赖于某种类型的集合的库方法的参数。
Collection
is also the supertype of List
, Queue
, Deque
, and others, so it gives you more options. For example, I try to use Collection
as a parameter to library methods that shouldn't explicitly depend on a certain type of collection.
一般来说,你应该使用正确的工具。如果你不想要重复,使用设置
(或 SortedSet
如果你想要排序或 LinkedHashSet
如果要维护插入顺序)。如果要允许重复,请使用列表
,依此类推。
Generally, you should use the right tool for the job. If you don't want duplicates, use Set
(or SortedSet
if you want ordering, or LinkedHashSet
if you want to maintain insertion order). If you want to allow duplicates, use List
, and so on.
这篇关于何时使用设置与集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!