简体   繁体   中英

What is the difference between Collection and Set interfaces in Java?

The declared method signatures seem to be equal. So what is the purpose of introducing Set interface rather then implementing Collection directly? Or is it just sort of a marker interface here?

Set guarantees that the collection will contain unique elements (no duplicates). A Collection does not guarantee this.

The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.

Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ. Two Set instances are equal if they contain the same elements.

The Set Interface

Note, Set does not preserve the order in which elements were inserted. You LinkedHashSet if you need to preserve insertion order of the elements. https://stackoverflow.com/a/821104/4587961

I guess I kind of understood what you want to know exactly. :)

Source code shipped with JDK (src.zip) has 2 interfaces, Collection and Set and all the methods declared in Collection interface are re-declared in Set interface. At first look it seems redundant to re-declare the methods. But if you look closely then you can find out that method signature is kept same as the Collection interface but comments are changed to describe what will be the behavior of methods in implementing classes.

Why Set interface exists if collection interface is sufficient enough in case of Set (as we are not introducing any new method in Set interface) (FYI: Here I'm ignoring one method which is introduced in Set interface - <T> T[] toArray(T[] a); ).

Ans : Lets say you have two classes ClassA and ClassB implementing Collection interface and both of them are storing unique elements (just like Set). Now you have a method lets say populateSet(Collection setImpl); and you have code specific to deal with your ClassA & ClassB, and purpose of this method is you can use this method to pass ClassA and ClassB interchangeably, so far everything is okay. But now the problem with this method is you can pass the ArrayList to this method as Collection interface is generic one and your methos will start breaking. Which is why we needed one more interface to categorize all the set implementation under the single hood.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM