Alex Rivera | Logout

when to use Set vs. Collection?

Asked 2009-05-04T17:34:52.407
51

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 Sets but not Collections?)

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.

  1. designing a method which accepts an argument of Set or Collection. 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 use Collection.)
  2. designing a method which returns a Set or Collection. Set offers more guarantees than Collection (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 use Set.)
  3. designing a class that implements the interface Set or Collection. Similar issues as #2. Users of my class/interface get more guarantees, subclassers/implementers have more responsibility.
  4. designing an interface that extends the interface Set or Collection. Very similar to #3.
  5. writing code that uses a Set or Collection. Here I might as well use Set; the only reasons for me to use Collection is if I get back a Collection from someone else's code, or if I have to handle a collection that contains duplicates.
Edit
Report

3 Answers

9

I think you already have it figured out- use a Set when you want to specifically exclude duplicates. Collection is generally the lowest common denominator, and it's useful to specify APIs that accept/return this, which leaves you room to change details later on if needed. However if the details of your application require unique entries, use Set to enforce this.

Also worth considering is whether order is important to you; if it is, use List, or LinkedHashSet if you care about order and uniqueness.

answered 2009-05-04T17:39:55.843
3

See Java's Collection tutorial for a good walk-through of Collection usage. In particular, check out the class hierarchy.

answered 2009-05-04T17:39:20.697
0

As Collection is a super type of Set and SortedSet these can be passed to a method which expects a Collection. Collection just means it may or may not be sorted, order or allow duplicates.

answered 2009-05-04T19:12:36.103

Your Answer