介绍:
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)
这些构造函数的用法都很直观。
让我们使用默认构造函数快速创建一个HashSet:
Set<Integer> set = new HashSet<>();
常用方法:
现在让我们看一些可以帮助我们操纵Java HashSet的方法:
1.
它只是将元素添加到给定的集合(如果尚不存在)。 如果该元素已经存在,则add()仅返回false:
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]
2.
如果元素在引用集中存在,则contains()方法返回true ,否则返回false :
System.out.println(set.contains(1)); //true
System.out.println(set.contains(4)); //false
3.
顾名思义,它将删除元素obj(如果存在)并返回true 。 如果不存在这样的元素,则仅返回false :
System.out.println(set.remove(1)); //true
System.out.println(set.remove(4)); //false
请注意, HashSet还继承了removeAll()和removeIf()方法,可用于删除值。
4.
对于空集返回true ,否则返回false :
System.out.println(set.isEmpty()); // false
5. int
它仅返回给定集中存在的元素数。
6.
clear()方法删除引用集中存在的所有值,从而使其成为空集。
内部实施:
HashSet在内部使用HashMap来存储其元素。 存储在HashSet中的元素被映射为HashMap中的键。 所有这些条目的值字段都包含一个常量PRESENT:
private static final Object PRESENT = new Object();
这是一个虚拟对象。
遍历
我们可以使用以下一种方式来迭代HashSet中的元素:
1.
从Java 8开始,我们可以使用forEach()遍历任何Java 集合:
set.forEach(e -> System.out.println(e));
2.
Java 8还支持forEachRemaining()构造,该构造可与Collection上的任何迭代器一起使用:
Iterator<Integer> itr = set.iterator();itr.forEachRemaining(e -> System.out.println(e));
3.使用
如果我们使用的是Java 7或更低版本,我们可以简单地使用迭代器进行迭代:
Iterator<Integer> itr = set.iterator();while(itr.hasNext()) {System.out.println(itr.next());
}
4.扩展
我们还可以使用扩展的for循环遍历元素:
for(Integer e : set) {System.out.println(e);
}
结论:
在本教程中,我们学习了如何创建和使用Java HashSet。 我们也知道Java HashSet在内部使用HashMap来实现它。
成为第一个发表评论的人。
翻译自: https://www.javacodegeeks.com/2019/04/hashset-java.html