Java HashSet
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 maintain the insertion order.
HashSet is not thread-safe. If multiple threads attempt to modify a HashSet concurrently, the final result is unpredictable. You must explicitly synchronize concurrent access to a HashSet when accessed by multiple threads.
HashSet implements the Set interface.
sites.remove("Taobao"); // Removes the element, returns true if successful, otherwise false
System.out.println(sites);
}
}
Executing the above code will output the following result:
[Google, tutorialpro, Zhihu]
To remove all elements from the collection, you can use the clear method:
Example
// Import HashSet class
import java.util.HashSet;
public class tutorialproTest {
public static void main(String[] args) {
HashSet<String> sites = new HashSet<String>();
sites.add("Google");
sites.add("tutorialpro");
sites.add("Taobao");
sites.add("Zhihu");
sites.add("tutorialpro"); // Duplicate elements will not be added
sites.clear();
System.out.println(sites);
}
}
Executing the above code will output the following result:
[]
Calculating Size
To calculate the number of elements in a HashSet, you can use the size() method:
Example
// Import HashSet class
import java.util.HashSet;
public class tutorialproTest {
public static void main(String[] args) {
HashSet<String> sites = new HashSet<String>();
sites.add("Google");
sites.add("tutorialpro");
sites.add("Taobao");
sites.add("Zhihu");
sites.add("tutorialpro"); // Duplicate elements will not be added
System.out.println(sites.size());
}
}
Executing the above code will output the following result:
4
Iterating Over HashSet
You can use a for-each loop to iterate over the elements in a HashSet.
Example
// Import HashSet class
import java.util.HashSet;
public class tutorialproTest {
public static void main(String[] args) {
HashSet<String> sites = new HashSet<String>();
sites.add("Google");
sites.add("tutorialpro");
sites.add("Taobao");
sites.add("Zhihu");
sites.add("tutorialpro"); // Duplicate elements will not be added
for (String i : sites) {
System.out.println(i);
}
}
}
Executing the above code will output the following result:
Google
tutorialpro
Zhihu
Taobao
For more API methods, you can refer to: https://www.tutorialpro.org/manual/jdk11api/java.base/java/util/HashSet.html