Java HashSet

Java 集合框架Java Collections Framework

HashSet is implemented based on HashMap and is a collection that does not allow duplicate elements.

HashSet allows null values.

HashSet is unordered, meaning it does not record the order of insertion.

HashSet is not thread-safe. If multiple threads attempt to modify a HashSet at the same time, the final result is uncertain. You must explicitly synchronize concurrent access to the HashSet when accessing it from multiple threads.

HashSet implements the Set interface.

The elements in a HashSet are actually objects. Some common basic types can use their wrapper classes.

The wrapper classes corresponding to basic types are as follows:

Basic typeReference type
booleanBoolean
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter

The HashSet class is located in the java.util package. You need to import it before use. The syntax format is as follows:

import java.util.HashSet; // 引入 HashSet 类

In the following example, we create a HashSet object sites to store string elements:

HashSet<String> sites = new HashSet<String>();

Add elements

The HashSet class provides many useful methods. You can use the add() method to add elements:

Example

// Import the HashSet class
import java.util.HashSet;

public class ExampleTest {
    public static void main(String[] args) {
    HashSet<String> sites = new HashSet<String>();
        sites.add("Google");
        sites.add("Example");
        sites.add("Taobao");
        sites.add("Zhihu");
        sites.add("Example");  // Duplicate elements will not be added
        System.out.println(sites);
    }
}

Execute the above code; the output result is as follows:

[Google, Example, Zhihu, Taobao]

In the above example, Example was added twice, but it appears only once in the collection because each element in the collection must be unique.

Check if an element exists

We can use the contains() method to determine whether an element exists in the collection:

Example

// Import the HashSet class
import java.util.HashSet;

public class ExampleTest {
    public static void main(String[] args) {
    HashSet<String> sites = new HashSet<String>();
        sites.add("Google");
        sites.add("Example");
        sites.add("Taobao");
        sites.add("Zhihu");
        sites.add("Example");  // Duplicate elements will not be added
        System.out.println(sites.contains("Taobao"));
    }
}

Execute the above code; the output result is as follows:

true

Delete elements

We can use the remove() method to delete elements from the collection:

Example

// Import the HashSet class
import java.util.HashSet;

public class ExampleTest {
    public static void main(String[] args) {
    HashSet<String> sites = new HashSet<String>();
        sites.add("Google");
        sites.add("Example");
        sites.add("Taobao");
        sites.add("Zhihu");
        sites.add("Example");     // Duplicate elements will not be added
        sites.remove("Taobao");  // Delete element; returns true if deletion is successful, otherwise false
        System.out.println(sites);
    }
}

Execute the above code; the output result is as follows:

[Google, Example, Zhihu]

To delete all elements in the collection, you can use the clear method:

Example

// Import the HashSet class
import java.util.HashSet;

public class ExampleTest {
    public static void main(String[] args) {
    HashSet<String> sites = new HashSet<String>();
        sites.add("Google");
        sites.add("Example");
        sites.add("Taobao");
        sites.add("Zhihu");
        sites.add("Example");     // Duplicate elements will not be added
        sites.clear();  
        System.out.println(sites);
    }
}

Execute the above code; the output result is as follows:

[]

Calculate size

To calculate the number of elements in a HashSet, you can use the size() method:

Example

// Import the HashSet class
import java.util.HashSet;

public class ExampleTest {
    public static void main(String[] args) {
    HashSet<String> sites = new HashSet<String>();
        sites.add("Google");
        sites.add("Example");
        sites.add("Taobao");
        sites.add("Zhihu");
        sites.add("Example");     // Duplicate elements will not be added
        System.out.println(sites.size());  
    }
}

Execute the above code; the output result is as follows:

4

Iterate HashSet

You can use for-each to iterate over the elements in a HashSet.

Example

// Import the HashSet class
import java.util.HashSet;

public class ExampleTest {
    public static void main(String[] args) {
    HashSet<String> sites = new HashSet<String>();
        sites.add("Google");
        sites.add("Example");
        sites.add("Taobao");
        sites.add("Zhihu");
        sites.add("Example");     // Duplicate elements will not be added
        for (String i : sites) {
            System.out.println(i);
        }
    }
}

Execute the above code; the output result is as follows:

Google
Example
Zhihu
Taobao

HashSet Common Methods

Method Return value Description Example
add(E e) boolean Add element to the collection; returns true on successtrue; returns false for duplicate elementsfalse。 set.add("Java");
remove(Object o) boolean Delete specified element; returns true on successtrue; returns false if element does not existfalse。 set.remove("Python");
contains(Object o) boolean Checks whether the collection contains the specified element. if (set.contains("Java")) { ... }
size() int Returns the number of elements in the collection. int count = set.size();
isEmpty() boolean Determines whether the collection is empty. if (set.isEmpty()) { ... }
clear() void Clears all elements in the collection. set.clear();
iterator() Iterator<E> Returns an iterator for the collection to traverse elements. for (String s : set) { ... }
toArray() Object[] Converts the collection to an array. Object[] arr = set.toArray();
toArray(T[] a) T[] Converts the collection to an array of the specified type. String[] arr = set.toArray(new String[0]);
addAll(Collection<? extends E> c) boolean Adds all elements of another collection (union operation). set.addAll(Arrays.asList("A", "B"));
retainAll(Collection<?> c) boolean Retains only the elements common with the specified collection (intersection operation). set.retainAll(otherSet);
removeAll(Collection<?> c) boolean Removes elements common with the specified collection (difference operation). set.removeAll(otherSet);

For more API methods, you can refer to:https://www.example.com/manual/jdk11api/java.base/java/util/HashSet.html

Java 集合框架Java Collections Framework

Other extensions