Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 788
Roman Avatar asked May 13 '26 06:05

Roman


1 Answers

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

like image 59
Yan Khonski Avatar answered May 15 '26 20:05

Yan Khonski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!