利用ConcurrentHashMap来实现一个ConcurrentHashSet详解编程语言

利用ConcurrentHashMap来实现一个ConcurrentHashSet

package hashset; 
 
import java.io.Serializable; 
import java.util.AbstractSet; 
import java.util.Iterator; 
import java.util.Set; 
import java.util.concurrent.ConcurrentHashMap; 
 
/** 
 * @author xfyou 
 * @date 2018/9/3 
 */ 
public class ConcurrentHashSet<E> extends AbstractSet<E> implements Set<E>, Serializable { 
 
    private static final long serialVersionUID = -8672117787651310382L; 
    private static final Object PRESENT = new Object(); 
 
    private final ConcurrentHashMap<E, Object> map; 
 
    public ConcurrentHashSet() { 
        this.map = new ConcurrentHashMap<>(); 
    } 
 
    public ConcurrentHashSet(int initialCapacity) { 
        this.map = new ConcurrentHashMap<>(initialCapacity); 
    } 
 
    @Override 
    public Iterator<E> iterator() { 
        return map.keySet().iterator(); 
    } 
 
    @Override 
    public boolean isEmpty() { 
        return map.isEmpty(); 
    } 
 
    @Override 
    public boolean contains(Object o) { 
        return map.containsKey(o); 
    } 
 
    @Override 
    public boolean add(E e) { 
        return map.put(e, PRESENT) == null; 
    } 
 
    @Override 
    public boolean remove(Object o) { 
        return map.remove(o) == PRESENT; 
    } 
 
    @Override 
    public void clear() { 
        map.clear(); 
    } 
 
    @Override 
    public int size() { 
        return map.size(); 
    } 
     
}

 

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/15902.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论