beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

HashSet Class in Java with example

By Chaitanya Singh | Filed Under: Java Collections

This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. This class is not synchronized. However it can be synchronized explicitly like this: Set s = Collections.synchronizedSet(new HashSet(...));

Points to Note about HashSet:

  1. HashSet doesn’t maintain any order, the elements would be returned in any random order.
  2. HashSet doesn’t allow duplicates. If you try to add a duplicate element in HashSet, the old value would be overwritten.
  3. HashSet allows null values however if you insert more than one nulls it would still return only one null value.
  4. HashSet is non-synchronized.
  5. The iterator returned by this class is fail-fast which means iterator would throw ConcurrentModificationException if HashSet has been modified after creation of iterator, by any means except iterator’s own remove method.

HashSet Example

import java.util.HashSet;
public class HashSetExample {
   public static void main(String args[]) {
      // HashSet declaration
      HashSet<String> hset = 
               new HashSet<String>();

      // Adding elements to the HashSet
      hset.add("Apple");
      hset.add("Mango");
      hset.add("Grapes");
      hset.add("Orange");
      hset.add("Fig");
      //Addition of duplicate elements
      hset.add("Apple");
      hset.add("Mango");
      //Addition of null values
      hset.add(null);
      hset.add(null);

      //Displaying HashSet elements
      System.out.println(hset);
    }
}

Output:

[null, Mango, Grapes, Apple, Orange, Fig]

As you can see there all the duplicate values are not present in the output including the duplicate null value.

HashSet tutorials

  • Delete all elements from HashSet
  • How to iterate through a HashSet
  • Convert a HashSet to an array
  • Convert a HashSet to a TreeSet
  • Convert HashSet to a List/ArrayList
  • HashSet vs HashMap
  • HashSet vs TreeSet

HashSet Methods:

  1. boolean add(Element  e): It adds the element e to the list.
  2. void clear(): It removes all the elements from the list.
  3. Object clone(): This method returns a shallow copy of the HashSet.
  4. boolean contains(Object o): It checks whether the specified Object o is present in the list or not. If the object has been found it returns true else false.
  5. boolean isEmpty(): Returns true if there is no element present in the Set.
  6. int size(): It gives the number of elements of a Set.
  7. boolean(Object o): It removes the specified Object o from the Set.

Reference

HashSet Documentation

Comments

  1. Mahesh says

    September 25, 2015 at 7:03 AM

    What is the difference between HashSet & ArrayList.

    Reply
    • Umesh says

      February 12, 2016 at 9:28 AM

      Array list is ordered collection and allowed duplicates where HashSet is not

      Reply
    • Abhay Kumar Dash says

      August 18, 2016 at 8:42 PM

      In Array List Dont follow default Sorting mechanism but In case Of Hash Set its possible and Insertion is not preserved in Hash set
      So the Collection Gives Facility for default sorting by using utility class ‘Collections’

      Reply
  2. Torben says

    November 14, 2015 at 9:01 PM

    quick and easy tutorial for java hashsets. thanks!

    Reply
  3. Marcos Lerin says

    February 9, 2016 at 9:11 PM

    I think this point is not correct:
    2.-HashSet doesn’t allow duplicates. If you try to add a duplicate element in HashSet, the old value would be overwritten.

    The Java docs mention: If this set already contains the element, the call leaves the set unchanged and returns false.

    Reply
  4. RAVI PRAKASH says

    February 18, 2016 at 9:22 AM

    Hash set can contains null value whereas array list cannot

    Reply
  5. ARNOLD says

    June 1, 2016 at 8:44 AM

    hello
    thanks for your site
    i have a Question
    how can
    Writing program with Hashset that show me
    Repetitive words ???

    Reply
  6. manish gour says

    June 3, 2016 at 1:07 PM

    This tutorial is superb, I like it.

    and It think by – “if HashSet has been modified after creation of iterator”
    You mean this:

    HashSet hs = new HashSet();

    Song s1 = new Song(“zzz”, “zaheer”, “23”, “343”);
    Song s2 = new Song(“xx”, “mosin”, “23”, “343”);

    hs.add(s1);
    hs.add(s2);

    Iterator itr = hs.iterator();

    Song s6 = new Song(“ooo”, “yakoob”, “23”, “343”);
    hs.add(s6);

    while (itr.hasNext()) {
    System.out.println(itr.next());
    }

    Reply
  7. shardul says

    November 24, 2016 at 10:29 AM

    ==================Hash List===================
    [null, Apple, Grapes, Fig, Mango, Orange]
    hi, I tried your code but it gets the result in sorted format.

    Reply
  8. Naja says

    August 11, 2017 at 6:55 AM

    can equal objects be added to hashset ? if yes then why it is not considered as duplicate ?

    Reply
  9. amin says

    December 15, 2017 at 6:37 AM

    thank you for the tutorial
    but the fact that ” If you try to add a duplicate element in HashSet, the old value would be overwritten.” is not true.
    according to what it says on oracle website in this link (https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html), it’s the other way around (i.e. if element_to_be_added is a duplicate, it won’t be added at all):

    public boolean add(E e)

    Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.

    Reply

Leave a Reply Cancel reply

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

Java Tutorial

  • Java Tutorial
  • OOPs Concepts

Java Collections

  • ArrayList
  • LinkedList
  • ArrayList vs LinkedList
  • Vector
  • ArrayList vs Vector
  • HashMap
  • TreeMap
  • LinkedHashMap
  • HashSet
  • TreeSet
  • LinkedHashSet
  • Hashtable
  • HashMap vs Hashtable
  • Queue
  • PriorityQueue
  • Deque & ArrayDeque
  • Iterator
  • ListIterator
  • Comparable Interface
  • Comparator Interface
  • Java Collections Interview Q

MORE ...

  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2019 BeginnersBook . Privacy Policy . Sitemap