What is Set interface in java

Set interface is a sub interface of Collection, under java.util package .It can use to store elements in a non duplicate manner .

Set interface  Set is an unordered collection , so the elements are not in the natural order .

Set interface  It won’t allow duplicate elements , but it allows null elements.

Set interface  We cannot get value by index or key .

Set interface  Set is not a synchronized collection , Use Collections.synchronizedSet(Set set) for synchronized Set .

Set interface and it’s implementations :

Set interface


All methods from Set :

Set interface



Set ‹generic type› ‹object name›= new <Set implemented class object>‹generic type›();

Example for Set interface :

Execution Result :


Few more methods:


Method Name Returns Description
addAll(Collection) boolean To add Collection of all elements .
containsAll(Collection) boolean Returns true ,if all Collection elements are present.
iterator() Iterator To iterate Set
removeAll(Collection) boolean To remove specified collection of elements .
retainAll(Collection) boolean Keeps the elements in Set , that are contained specified Collection
toArray() Object[] Returns Array of  elements .
toArray(T[] t) T[] Returns specified array(ex:String[]) of elements.

Set interface We cannot get identical elements from the Set .
Set interface Some implementations of the Set having restrictions on elements .
Set interface Implemented classes of The Set interface having  additional search features .

Related Posts :
What is an interface and how to work with an interface in java
What is the difference between interface and abstract class in java
What is Map interface in java
What is List interface in java
Difference between Set and Map
Difference between List and Set
   [will not be published]

^ <