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.
(For example, does Set
give me more options to use libraries which accept Set
s but not Collection
s?)
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.
- 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.
Best Answer
Collection
is also the supertype ofList
,Queue
,Deque
, and others, so it gives you more options. For example, I try to useCollection
as a parameter to library methods that shouldn't explicitly depend on a certain type of collection.Generally, you should use the right tool for the job. If you don't want duplicates, use
Set
(orSortedSet
if you want ordering, orLinkedHashSet
if you want to maintain insertion order). If you want to allow duplicates, useList
, and so on.