1 package cz.cuni.amis.utils.sets; 2 3 import java.util.Collection; 4 import java.util.Iterator; 5 import java.util.Set; 6 import java.util.concurrent.ConcurrentHashMap; 7 8 public class ConcurrentHashSet<K> implements Set<K>{ 9 10 private ConcurrentHashMap<K, K> map = new ConcurrentHashMap<K, K>(); 11 12 public ConcurrentHashSet() { 13 } 14 15 @Override 16 public boolean add(K e) { 17 boolean contains = map.containsKey(e); 18 map.put(e,e); 19 return !contains; 20 } 21 22 @Override 23 public boolean addAll(Collection<? extends K> c) { 24 boolean changed = false; 25 for (K element : c) { 26 changed = add(element) || changed; 27 } 28 return changed; 29 } 30 31 @Override 32 public void clear() { 33 map.clear(); 34 } 35 36 @Override 37 public boolean contains(Object o) { 38 return map.containsKey(o); 39 } 40 41 @Override 42 public boolean containsAll(Collection<?> c) { 43 for (Object o : c) { 44 if (!contains(o)) return false; 45 } 46 return true; 47 } 48 49 @Override 50 public boolean isEmpty() { 51 return map.size() == 0; 52 } 53 54 @Override 55 public Iterator<K> iterator() { 56 return map.values().iterator(); 57 } 58 59 @Override 60 public boolean remove(Object o) { 61 return map.remove(o) != null; 62 } 63 64 @Override 65 public boolean removeAll(Collection<?> c) { 66 boolean changed = false; 67 for (Object o : c) { 68 changed = remove(o) || changed; 69 } 70 return changed; 71 } 72 73 @Override 74 public boolean retainAll(Collection<?> c) { 75 clear(); 76 for (Object element : c) { 77 add((K) element); 78 } 79 return true; 80 } 81 82 @Override 83 public int size() { 84 return map.size(); 85 } 86 87 @Override 88 public Object[] toArray() { 89 return map.values().toArray(); 90 } 91 92 @Override 93 public <T> T[] toArray(T[] a) { 94 return map.values().toArray(a); 95 } 96 97 }