Java Set Interface

tutorial and example
tutorial and example

JAVA SET INTERFACE

We use set when we don’t want to allow duplicate entries. All Set implementations do not allow duplicates.

  • HashSet : This class stores its elements in a hash tables. It uses hashCode() method to find the objects. This class has the benefit that addition and checking the presence of an element has constant time. The disadvantage is that, we lose the order of insertion of the elements.
  • LinkedHashSet : Java LinkedHashSet class is a Hash table and Linked list            implementation of the set interface. It inherits HashSet class and implements Set interface.
  • TreeSet : This class stores its elements in a sorted tree structure. The benefit is that elements are always in sorted order but addition and checking the presence of an element takes longer time O(log n). TreeSet implements a special interface called NavigableSet.

Useful Methods

Modifier and Type

Method

Description

boolean

add(E e)

It adds the specified element to this set if it is not already present (optional operation).

boolean

addAll(Collection<? extends E> c)

It adds all of the elements in the specified collection to this set if they’re not already present (optional operation).

void

clear()

It removes all of the elements from this set (optional operation).

boolean

contains(Object o)

It returns true if this set contains the specified element.

boolean

remove(Object o)

It removes the specified element from this set if it is present (optional operation).

boolean

equals(Object o)

It compares the specified object with this set for equality.

int

hashCode()

It returns the hash code value for this set.

boolean

isEmpty()

It returns true if this set contains no elements.

Iterator<E>

iterator()

It returns an iterator over the elements in this set.

Example: HashSet

Output:

Example: LinkedHashSet

Output:

Example: TreeSet

Output: