What's the purpose of java.util.Set interface if it contains absolutely equal methods in comparison with java.util.Collection? There is no prohibition for multi-implementing in Java, and Set realization (HashSet) could work fine without Set interfaces. So why do we need that useless baggage?
- there's 7 other classes that implement the interface, not just hashset AbstractSet, ConcurrentSkipListSet, CopyOnWriteArraySet, EnumSet, JobStateReasons, LinkedHashSet, TreeSetJeff Hawthorne– Jeff Hawthorne2013-02-06 20:32:13 +00:00Commented Feb 6, 2013 at 20:32
- You're right, but nevertheless - were those classes able to implement Collection interface and forget about Set or not?gabriel angelos– gabriel angelos2013-02-06 20:33:59 +00:00Commented Feb 6, 2013 at 20:33
Add a comment |
2 Answers
JavaDoc describing contract of Collection (emphasis mine):
A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not.
On Set:
A collection that contains no duplicate elements.
In other words, Set abstraction describes a (ekhem!) subset of Collections.
2 Comments
gabriel angelos
You mean that was made to protect methods that take (Set) as an argument from passing List's realizations ?
Tomasz Nurkiewicz
@user2033357: that means that if you implement
Set interface you must obey the contract (thus, don't allow duplicates). If you implement Collection only (not Set) you are free to accept duplicates. It doesn't enforce anything, it basically documents what you can accept on every implementation. If some implementation of Set allows duplicates, it's broken by definition.