📜  Java HashSet(1)

📅  最后修改于: 2023-12-03 15:01:30.231000             🧑  作者: Mango

Java HashSet

Java HashSet is a class in the Java Collection Framework that implements the Set interface. It uses a hash table for storage and provides constant-time performance for the basic operations (add, remove, contains, and size) under the assumption that the hash function disperses the elements properly among the buckets.

Creating a HashSet

To create a HashSet, you can use the default constructor, which creates an empty HashSet with a default initial capacity of 16 and a load factor of 0.75:

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

You can also create a HashSet with a specified initial capacity and load factor:

HashSet<String> set = new HashSet<>(20, 0.85f);
Adding Elements

To add elements to a HashSet, use the add method:

set.add("apple");
set.add("banana");
set.add("orange");
Removing Elements

To remove elements from a HashSet, use the remove method:

set.remove("banana");
Checking if an Element Exists

To check if an element exists in a HashSet, use the contains method:

boolean exists = set.contains("orange");
Retrieving the Size

To retrieve the number of elements in a HashSet, use the size method:

int size = set.size();
Iterating over Elements

To iterate over the elements in a HashSet, you can use a for-each loop:

for (String element : set) {
    System.out.println(element);
}
Conclusion

Java HashSet is a useful class in the Java Collection Framework that provides constant-time performance for basic operations. It is particularly useful when you need to maintain a collection of unique elements with no duplicates.