使用哈希表进行存储的集合通常由 Java HashSet类创建。 顾名思义,HashSet实现Set接口,并且还使用一个哈希表,该哈希表是HashMap实例。HashSet中元素的顺序是随机的。 此类允许使用null元素。 就复杂度而言,HashSet为基本操作(如添加,删除,包含和大小)提供恒定的时间性能,前提是假定元素已被函数正确分散。

有关HashSet的重要信息
HashSet通过使用称为散列的机制来存储元素。HashSet中不能存在重复的元素。HashSet允许为空值。HashSet类不同步。HashSet的顺序不由插入顺序维护。 元素(在此类中)是根据其哈希码插入的。- 就搜索操作而言,由于
HashSet具有恒定的时间复杂度,因此它是最好的方法。 HashSet的初始默认容量为 16,而负载系数为 0.75。
HashSet简单的结构图

Java 中的HashSet
我们放入HashMap中的每个对象都首先通过哈希算法发送。 该算法的唯一目的是为传递给它的每个对象生成一个称为哈希的唯一编号。 在上图中,此算法为字符串Lisa Morgan生成了数字 3,为Bob Wiliams生成了数字 2,为Jane Smith生成了数字 1。 以后,这些数字将作为索引存储在数组中。 每当您要对HashSet中的元素执行任何类型的操作时,您都将通过由哈希算法生成的索引来解决它们。 这就是HashSet以随机顺序返回元素的原因。 哈希号是HashSet知道的唯一顺序。
HashSet中的构造方法
HashSet hashSet = new HashSet();HashSet hashSet = new HashSet(int initialCapacity);HashSet hashSet = new HashSet(int initialCapacity, float loadFactor);HashSet hashSet = new HashSet(Collection c);
这些构造函数之间的主要区别在于,在 #1 构造函数中,初始容量为 16,默认负载因子为 0.75,但在 #2 中,您实际上可以设置容量。 负载系数的默认值仍为 0.75。 在构造函数 3 中,您可以设置容量和负载系数。
HashSet类中的方法
boolean add(Object o):用于添加作为参数提供的元素,如果不存在,则返回false。void clear():用于删除所有元素。boolean contains(Object o):如果指定的Object在HashSet中,则返回true;否则,返回false。boolean remove(Object o):用于从HashSet中删除指定的Object(如果存在)。Iterator iterator():用于返回集合中元素上的迭代器。boolean isEmpty():用于检查HashSet是否为空。 如果为空,则返回true;否则为false。int size():返回集合的大小。Object clone():创建集合的副本。
有关所有方法的文档,请访问 Oracle 官方文档页面。
使用add()在HashSet中添加元素
语法:HashSet.add(Object o);
import java.io.*;import java.util.HashSet;public class HashSetExample {public static void main(String args[]){// Creating an empty HashSetHashSet<String> animals = new HashSet<String>();animals.add("Elephant");animals.add("Tiger");animals.add("Lion");// Displaying the HashSetSystem.out.println("HashSet: " + animals);}}
输出:
HashSet: [Elephant, Tiger, Lion]
使用clear()清空HashSet
语法:HashSet.clear();
输出:
import java.io.*;import java.util.HashSet;public class HashSetExample{public static void main(String args[]){// Creating an empty HashSetHashSet<String> animals = new HashSet<String>();animals.add("Elephant");animals.add("Tiger");animals.add("Lion");// Displaying the HashSetSystem.out.println("HashSet: " + animals);// Clearing the hash setanimals.clear();// Displaying the final Set after clearing;System.out.println("The final set: " + animals);}}
HashSet: [Elephant, Tiger, Lion]The final set: []
使用contains()检查HashSet中是否存在元素
语法:Hash_Set.contains(Object o)
import java.io.*;import java.util.HashSet;public class HashSetExample {public static void main(String args[]){// Creating an empty HashSetHashSet<String> animals = new HashSet<String>();animals.add("Elephant");animals.add("Tiger");animals.add("Lion");// Displaying the HashSetSystem.out.println("HashSet: " + animals);// Checking for "Lion" in the hash setSystem.out.println("Does the HashSet contain 'Lion'? " + animals.contains("Lion"));// Checking for "Elephant" in the hash setSystem.out.println("Does the HashSet contain 'Elephant'? " + animals.contains("Elephant"));// Checking for "Tiger" in the hash setSystem.out.println("Does the HashSet contain 'Tiger'? " + animals.contains("Tiger"));// Checking for "Chicken" in the hash setSystem.out.println("Does the HashSet contain 'Chicken'? " + animals.contains("Chicken"));}}
输出:
HashSet: [Elephant, Tiger, Lion]Does the Set contain 'Lion'? trueDoes the Set contain 'Elephant? trueDoes the Set contain 'Tiger'? trueDoes the Set contain 'Chicken'? false
使用remove()从HashSet中删除元素
语法:HashSet.remove(Object o)
import java.util.*;import java.util.HashSet;public class HashSetExample {public static void main(String args[]){// Creating an empty HashSetHashSet<String> animals = new HashSet<String>();animals.add("Elephant");animals.add("Tiger");animals.add("Lion");// Displaying the HashSetSystem.out.println("HashSet: " + animals);set.remove("Elephant");set.remove("Lion");// Displaying the HashSet after removalSystem.out.println("HashSet after removing elements: " + animals);}}
输出:
HashSet: [Elephant, Tiger, Lion]HashSet after removing elements: [Tiger]
Iterator()方法
语法:Iterator iterator = HashSet.iterator();
import java.util.*;import java.util.HashSet;public class HashSetExample {public static void main(String args[]){// Creating an empty HashSetHashSet<String> animals = new HashSet<String>();animals.add("Elephant");animals.add("Tiger");animals.add("Lion");// Displaying the HashSetSystem.out.println("HashSet: " + animals);// Creating an iteratorIterator iterator = animals.iterator();// Displaying the values after iterating through the setSystem.out.println("The iterator values are: ");while (iterator.hasNext()) {System.out.println(iterator.next());}}}
输出:
HashSet: [Elephant, Tiger, Lion]The iterator values are:ElephantTigerLion
使用isEmpty()检查HashSet是否为空
语法:HashSet.isEmpty();
import java.io.*;import java.util.HashSet;public class HashSetExample {public static void main(String args[]){// Creating an empty HashSetHashSet<String> animals = new HashSet<String>();animals.add("Elephant");animals.add("Tiger");animals.add("Lion");// Displaying the HashSetSystem.out.println("HashSet: " + animals);// Check for the empty setSystem.out.println("Is the hash set empty: " + animals.isEmpty());set.clear();// Checking after we've cleared it outSystem.out.println("Is the hash set empty: " + animals.isEmpty());}}
输出:
HashSet: [Elephant, Tiger, Lion]Is the hash set empty: falseIs the hash set empty: true
使用size()获取HashSet的大小
语法:HashSet.size();
import java.util.*;import java.util.HashSet;public class HashSetExample {public static void main(String args[]){// Creating an empty HashSetHashSet<String> animals = new HashSet<String>();animals.add("Elephant");animals.add("Tiger");animals.add("Lion");// Displaying the HashSetSystem.out.println("HashSet: " + animals);// Get the size of the hash setSystem.out.println("The size of the hash set is: " + animals.size());}}
输出:
HashSet: [Elephant, Tiger, Lion]The size of the hash set is: 3
使用clone()克隆HashSet
语法:HashSet.clone()
import java.io.*;import java.util.HashSet;public class HashSetExample {public static void main(String args[]){// Creating an empty HashSetHashSet<String> animals = new HashSet<String>();animals.add("Elephant");animals.add("Tiger");animals.add("Lion");System.out.println("HashSet: " + animals);// Creating a new setHashSet clonedSet = new HashSet();// Cloning the set using clone() methodclonedSet = (HashSet)animals.clone();// Displaying the new hashset;System.out.println("The new set: " + clonedSet);}}
输出:
HashSet: [Elephant, Tiger, Lion]The new set: [Elephant, Tiger, Lion]
如何迭代HashSet
有两种方法可以遍历HashSet:
- 使用迭代器
- 不使用迭代器
1)使用迭代器
import java.util.HashSet;import java.util.Iterator;class IterateHashSetExample{public static void main(String[] args) {HashSet<String> animals= new HashSet<String>();//add elements to HashSetanimals.add("Elephant");animals.add("Tiger");animals.add("Lion");Iterator<String> iterator = animals.iterator();while(iterator.hasNext()){System.out.println(iterator.next());}}}
上面的代码只是将迭代器“附加”到动物散列集上,然后仅打印每一个迭代器,直到没有更多为止。 另外,此方法将忽略重复项。 如果有重复项,则重复项仅打印一次。
输出:
ElephantTigerLion
2)不使用迭代器
import java.util.HashSet;import java.util.Set;class IterateHashSetExample{public static void main(String[] args) {Set<String> animals = new HashSet<String>();//add elements to HashSetanimals.add("Elephant");animals.add("Tiger");animals.add("Lion");for (String animal : animals) {System.out.println(animal);}}}
输出:
ElephantTigerLion
