Java.util.HashSet Example


Introduction

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.

A hash table stores information by using a mechanism called hashing.

HashSet stores the elements by using a mechanism called hashing.

In hashing, the informational content of a key is used to determine a unique value, called its hash code.

HashSet contains unique elements only.

Difference Between Set And List in Java

Declaration of java.util.HashSet

public class HashSet
extends AbstractSet
implements Set, Cloneable, java.io.Serializable
{
...
}

Example of java.util.HashSet

import java.util.HashSet;
import java.util.Iterator;

public class main {

public static void main (String [] args)
{
//declare a default HashSet object
HashSet set=new HashSet<>();

//add elements to this set
set.add("Item 1");
set.add("Item 2");
set.add("Item 3");

System.out.println("number of elements in this set : " + set.size());

System.out.println(set);
//output : [Item 3, Item 2, Item 1]

//return an iterator over the elements in this set
Iterator iterator =set.iterator();

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

Output from The Program

number of elements in this set : 3
[Item 3, Item 2, Item 1]
Item 3
Item 2
Item 1


Java HashSet class

張貼留言

1 留言

  1. Detailed explanation on java.util.HashSet.
    Thanks,
    https://www.flowerbrackets.com/hashset-in-java/

    回覆刪除