Java中的HashSet实现了Set接口,即它不允许重复。它由HashMap 内部支持,它基于散列原理工作。
我们可以在HashSet中存储一个 空值。其默认容量为16,负载系数为0.75,其中:
Load factor = Number of Stored Elements / capacity
Java HashSet是非同步的也就是说是非线程安全的。此外,无法保证保留元素的插入顺序。
在本教程中,我们将学习如何使用Java HashSet。
我们可以使用以下构造函数之一创建Java HashSet:
HashSet() // default capacity of 16 with a load factor of 0.75
HashSet(int initialCapacity)
HashSet(int initialCapacity, float loadFactor)
HashSet(Collection c)
这些构造函数中的每一个都非常直观。Set<Integer> set = new HashSet<>();
现在让我们看一些可以帮助我们操作Java HashSet的方法:
System.out.println(set.add(1)); //true
System.out.println(set.add(2)); //true
System.out.println(set.add(3)); //true
System.out.println(set.add(1)); //false - as already present
//Note that the order of elements isn't guaranteed
System.out.println(set); //[1, 2, 3]
System.out.println(set.contains(1)); //true
System.out.println(set.contains(4)); //false
System.out.println(set.remove(1)); //true
System.out.println(set.remove(4)); //false
System.out.println(set.isEmpty()); // false
private static final Object PRESENT = new Object();
这是一个虚拟对象set.forEach(e -> System.out.println(e));
Iterator<Integer> itr = set.iterator();
itr.forEachRemaining(e -> System.out.println(e));
Iterator<Integer> itr = set.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
}
for(Integer e : set) {
System.out.println(e);
}
http://blog.xqlee.com/article/578.html