Java Set Interface

Category: Java   Tags: Java, Java Collection, Java Set Interface

The Set interface extends Collection and does not allow duplicate elements. Set is a generic interface:

                          interface Set<E>

Here, E specifies the type of objects that the set will contain.


In addition to the methods defined by Collection, Set defines some of its own:

boolean add(E element)
Add the specified element to this set if it is not already present and returns true. If the element is already present then this set will be unchanged and false will be returned.
Iterator iterator()
It returns an iterator that will do the iteration from the starting position of the invoking set. Order of elements are uncertain unless this set is an instance of some specific class that maintain order.
boolean remove(Object element)
Removes the specified element from this set if it is present.
boolean addAll(Collection<? extends E> c)
Adds all of the elements in the specified collection c to this set if they're not already present and returns true if the set changed.
void clear()
Removes all of the elements from this set.
boolean isEmpty()
Returns true if this set contains no element.
int size()
Returns the size of this set.
boolean equals(Object o)
Compares the specified object with this set for equality and returns true if both are equal.
boolean contains(Object element)
It returns true if this set contains the specified element else false is returned.
Object[] toArray()
It returns an array containing all of the elements in this set. Modifying the returned array keeps the original set unaffected.
boolean containsAll(Collection<?> c)
Returns true if this set contains all of the elements of the specified collection c.

Some commonly used classes that implement Set interface are: HashSet, LinkedHashSet, TreeSet.