JDK 8 - java.util.HashSet 实现机制分析

JDK 8  Class HashSet<E> Doc:
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, Serializable

 

1、实现了java.util.Set接口,内部由java.util.Map示例实现(允许null值)

2、不保证迭代顺序,也不保证迭代顺序一直不变

3、非同步;必须从外部同步,比如:Set s = Collections.synchronizedSet(new HashSet());

4、iterator()返回的iterator是fail-fast的:如果这个iterator创建以后,这个set被修改了(不是这个iterator的remove()方法修改的),那么会抛出ConcurrentModificationException异常。(注意,这个fail-fast也是无法保证的,因为在非同步的并发修改中,没有什么是可以保证的)

 

UML Class Diagram:

UML Class Diagram for HashSet

 

HashSet 内部有一个变量:

1 private transient HashMap<E,Object> map;

HashSet 的所有操作最后都是委托给了这个 hashmap。

 

1、添加元素

1     public boolean add(E e) {
2         // 到 map 中查找,key==e && value==PRESENT 
3         return map.put(e, PRESENT)==null;
4     }

 

2、删除元素

1     public boolean remove(Object o) {
2         // 从 map 中删除 key==o 的元素,其中 key==o 对应的 value==PRESENT
3         return map.remove(o)==PRESENT;
4     }  

3、查找元素

1     public boolean contains(Object o) {
2         // 到 map 中查找,key==o 
3         return map.containsKey(o);
4     }

 

常见操作:

OperationsTime ComplexityNotes
add, remove, contains, sizeO(1)assuming the hash functions has dispersed the elements properly among the buckets
iterationproportional to the number of the elememts and bucketsdo not set the initial capacity too high(or the load factor too low) for the iteration-critical program
  • Implementing the java.util.Set interface, internally backed by a java.util.HashMap instance(permitting null values).
  • Making no guarantees to the iteration order and the constantness of the order over time either.
  • Not synchronized; must be synchronized externally, for example: Set s =  Collections.synchronizedSet(new HashSet());
  • Iterators returned by the iterator() method are fail-fast: it will throw a ConcurrentModificationException if the set is modified after the creation of the iterator and by any method except through the iterator's remove() method. Notice that the fail-fast behavior cannot be guaranteed because nothing can be guaranteed in the presence of unsynchronized concurrent modification.

 

 

转载于:https://www.cnblogs.com/huangzejun/p/8143374.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值