Java HashSet class

Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements Set interface.

The important points about Java HashSet class are:

  • HashSet stores the elements by using a mechanism called hashing.
  • HashSet contains unique elements only.
  • HashSet class declaration

    public class HashSet extends AbstractSet implements Set, Cloneable, Serializable

    Constructors of Java HashSet class:

    HashSet() It is used to construct a default HashSet.

    HashSet(Collection c) It is used to initialize the hash set by using the elements of the collection c.

    HashSet(int capacity) It is used to initialize the capacity of the hash set to the given integer value capacity. The capacity grows automatically as elements are added to the HashSet.

    Methods of Java HashSet class:

    1. void clear()

      It is used to remove all of the elements from this set.

    2. boolean contains(Object o)

      It is used to return true if this set contains the specified element.

    3. boolean add(Object o)

      It is used to adds the specified element to this set if it is not already present.

    4. boolean isEmpty()

      It is used to return true if this set contains no elements.

    5. boolean remove(Object o)

      It is used to remove the specified element from this set if it is present.

    EXAMPLE

    Flash Soon



    Advertisement

    Copyright ©2017 Design& develop