Set in Java

Posted on Updated on

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:

  1. java.util.HashSet
  2. java.util.LinkedHashSet
  3. java.util.TreeSet

Methods of Set interface

Method Name 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

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.