[英]How Hashset avoids duplicates
HashSet internally calling HashMap to avoid duplicates in the implementation HashSet内部调用HashMap以避免实现中的重复
public HashSet() {
map = new HashMap<E,Object>();
}
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
For Example 例如
Code: 码:
Set hashSet = new HashSet();
hashSet.add("Abraham");
hashSet.add("Billy");
hashSet.add("Billy");
System.out.println("HashSet Value " +hashSet.toString());
Output: 输出:
HashSet Value [Billy, Abraham]
In the Map
interface, each key is also unique ( java docs ): 在
Map
界面中,每个键也是唯一的( java docs ):
An object that maps keys to values.
将键映射到值的对象。 A map cannot contain duplicate keys ;
映射不能包含重复的键 ; each key can map to at most one value.
每个键最多可以映射到一个值。
This means, the HashMap
is already taking care of avoiding duplicate keys, which are the elements of the HashSet
这意味着
HashMap
已经在避免避免重复的键,这是HashSet
的元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.