Set in Java
Set interface is a collection that doesn’t allow duplicate element. It contains only methods inherited from collection and add restriction to prohibites duplicate elements.A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the set.
Since Set is an interface we need to instantiate a concrete implementation of the interface in order to use it. following are Set implementations in the Java Collections API:
- java.util.HashSet
- java.util.LinkedHashSet
- java.util.TreeSet
Methods of Set interface
Method | Description |
---|---|
add(Object obj) | Adds an object to the collection. |
clear() | Removes all elements from the collection. |
contains(Object obj) | Returns true if specified object is available with the collection. |
isEmpty() | Returns true if the collection has no elements. |
remove(Object obj) | Removes a specified object from the collection. |
size() | Returns number of elements in the collection. |
iterator() | Returns an Iterator object for the collection which may be used to retrieve an object |