Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java HashSet

Java HashSet

Java Collections Framework At this point, the trimToSize() method can remove the unallocated space and change the capacity of the ArrayList so that it equals the number of elements in the ArrayList.

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 insertion order.

HashSet is not thread-safe. If multiple threads attempt to modify the HashSet at the same time, the final result is undefined. You must explicitly synchronize concurrent access to the HashSet in multi-threaded access.

HashSet implements the Set interface.

Elements in a HashSet are actually objects; some common primitive types can use their wrapper classes.

can only be a reference data type, then we need to use the wrapper classes of the primitive types.

Basic types Reference type
boolean Boolean
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character

The HashSet class is in the java.util package and must be imported before use, as shown in the following syntax:

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

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

HashSet sites = new HashSet();

Adding elements

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

Example

// Import the HashSet class      

import

java.util.HashSet

;

public

class

RunoobTest

{

   

public

static

void

main

(

String

[

]

args

)

{

    HashSet

<

String

sites

=

new

HashSet

<

String

(

)

;

        sites.

add

(

"Google"

)

;

        sites.

add

(

"Runoob"

)

;

        sites.

add

(

"Taobao"

)

;

        sites.

add

(

"Zhihu"

)

;

        sites.

add

(

"Runoob"

)

;

 

// Duplicate elements will not be added

       

System

.

out

.

println

(

sites

)

;

   

}

}

After executing the above code, the output is as follows:

[Google, Runoob, Zhihu, Taobao]

In the example above, Runoob is added twice, but it appears only once in the collection, because every element in a set must be unique.

Check Whether an Element Exists

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

Example

// Import the HashSet class      

import

java.util.HashSet

;

public

class

RunoobTest

{

   

public

static

void

main

(

String

[

]

args

)

{

    HashSet

<

String

sites

=

new

HashSet

<

String

(

)

;

        sites.

add

(

"Google"

)

;

        sites.

add

(

"Runoob"

)

;

        sites.

add

(

"Taobao"

)

;

        sites.

add

(

"Zhihu"

)

;

        sites.

add

(

"Runoob"

)

;

 

// Duplicate elements will not be added

       

System

.

out

.

println

(

sites.

contains

(

"Taobao"

)

)

;

   

}

}

After executing the above code, the output 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

RunoobTest

{

   

public

static

void

main

(

String

[

]

args

)

{

    HashSet

<

String

sites

=

new

HashSet

<

String

(

)

;

        sites.

add

(

"Google"

)

;

        sites.

add

(

"Runoob"

)

;

        sites.

add

(

"Taobao"

)

;

        sites.

add

(

"Zhihu"

)

;

        sites.

add

(

"Runoob"

)

;

   

// Duplicate elements will not be added

        sites.

remove

(

"Taobao"

)

;

 

// Delete an element; returns true on success, otherwise false

       

System

.

out

.

println

(

sites

)

;

   

}

}

After executing the above code, the output is as follows:

[Google, Runoob, 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

RunoobTest

{

   

public

static

void

main

(

String

[

]

args

)

{

    HashSet

<

String

sites

=

new

HashSet

<

String

(

)

;

        sites.

add

(

"Google"

)

;

        sites.

add

(

"Runoob"

)

;

        sites.

add

(

"Taobao"

)

;

        sites.

add

(

"Zhihu"

)

;

        sites.

add

(

"Runoob"

)

;

   

// Duplicate elements will not be added

        sites.

clear

(

)

;

 

       

System

.

out

.

println

(

sites

)

;

   

}

}

After executing the above code, the output is as follows:

[]

// Delete the fourth element

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

Example

// Import the HashSet class      

import

java.util.HashSet

;

public

class

RunoobTest

{

   

public

static

void

main

(

String

[

]

args

)

{

    HashSet

<

String

sites

=

new

HashSet

<

String

(

)

;

        sites.

add

(

"Google"

)

;

        sites.

add

(

"Runoob"

)

;

        sites.

add

(

"Taobao"

)

;

        sites.

add

(

"Zhihu"

)

;

        sites.

add

(

"Runoob"

)

;

   

// Duplicate elements will not be added

       

System

.

out

.

println

(

sites.

size

(

)

)

;

 

   

}

}

After executing the above code, the output is as follows:

4

Iterating Over a 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

RunoobTest

{

   

public

static

void

main

(

String

[

]

args

)

{

    HashSet

<

String

sites

=

new

HashSet

<

String

(

)

;

        sites.

add

(

"Google"

)

;

        sites.

add

(

"Runoob"

)

;

        sites.

add

(

"Taobao"

)

;

        sites.

add

(

"Zhihu"

)

;

        sites.

add

(

"Runoob"

)

;

   

// Duplicate elements will not be added

       

for

(

String

i

:

sites

)

{

           

System

.

out

.

println

(

i

)

;

       

}

   

}

}

After executing the above code, the output is as follows:


Google
Runoob
Zhihu
Taobao

Common HashSet Methods

Method Return Value Description Example
add(E e) boolean Add an element to the collection; returns on success true, returns for duplicate elements false. set.add("Java");
remove(Object o) boolean Remove the specified element; returns on success true, returns if the element does not exist false. set.remove("Python");
contains(Object o) boolean Check whether the collection contains the specified element. if (set.contains("Java")) { ... }
size() int Return the number of elements in the collection. int count = set.size();
isEmpty() boolean Determine whether the collection is empty. if (set.isEmpty()) { ... }
clear() void Remove all elements from the collection. set.clear();
iterator() Iterator Return the iterator of the collection for traversing elements. for (String s : set) { ... }
toArray() Object[] Convert the collection to an array. Object[] arr = set.toArray();
toArray(T[] a) T[] Convert the collection to an array of a specified type. String[] arr = set.toArray(new String[0]);
addAll(Collection c) boolean Add all elements of another collection (union operation). set.addAll(Arrays.asList("A", "B"));
retainAll(Collection c) boolean Retain only the elements common to the specified collection (intersection operation). set.retainAll(otherSet);
removeAll(Collection c) boolean Remove the elements common to the specified collection (set difference operation). set.removeAll(otherSet);

Traverse every element in the arraylist and perform a specific operationhttps://www.runoob.com/manual/jdk11api/java.base/java/util/HashSet.html

Java Collections Framework At this point, the trimToSize() method can remove the unallocated space and change the capacity of the ArrayList so that it equals the number of elements in the ArrayList.