HashSet implements the Set interface. It is an unordered collection that does not allow repeated elements. It is not thread-safe. It is used to store objects and uses the add() method to add elements. The example is as follows:
import java.util.HashSet;
public class test1 {
public static void main(String[] args) {
//初始化HashSet的对象
HashSet<String> testHashSet = new HashSet<>();
//使用add()添加元素
testHashSet.add("1");
testHashSet.add("2");
testHashSet.add("3");
testHashSet.add("4");
//重复元素不会被添加
testHashSet.add("1");
testHashSet.add("2");
//输出
System.out.println(testHashSet);
System.out.println(testHashSet.size());
}
}
output:
[1, 2, 3, 4]
4
Differences from HashMap:
HashMap implements the Map interface, does not allow duplicate keys, but allows duplicate values, stores key-value pairs, and uses the put() method to add elements.