1 22 package org.jboss.util.collection; 23 24 import java.lang.ref.ReferenceQueue ; 25 26 import java.util.Set ; 27 import java.util.HashSet ; 28 import java.util.AbstractSet ; 29 import java.util.Iterator ; 30 import java.util.NoSuchElementException ; 31 32 import org.jboss.util.NullArgumentException; 33 import org.jboss.util.WeakObject; 34 35 45 public class WeakSet 46 extends AbstractSet 47 implements Set 48 { 49 50 protected final ReferenceQueue queue = new ReferenceQueue (); 51 52 53 protected final Set set; 54 55 63 public WeakSet(final Set set) { 64 if (set == null) 65 throw new NullArgumentException("set"); 66 67 if (set.size() != 0) { 69 Object elements[] = set.toArray(); 70 set.clear(); 71 72 for (int i=0; i<elements.length; i++) { 73 add(elements[i]); 74 } 75 } 76 77 this.set = set; 78 } 79 80 83 public WeakSet() { 84 this(new HashSet ()); 85 } 86 87 91 protected final void maintain() { 92 WeakObject weak; 93 while ((weak = (WeakObject)queue.poll()) != null) { 94 set.remove(weak); 95 } 96 } 97 98 103 public int size() { 104 maintain(); 105 106 return set.size(); 107 } 108 109 114 public Iterator iterator() { 115 return new Iterator () { 116 117 118 Iterator iter = set.iterator(); 119 120 121 Object next = null; 122 123 public boolean hasNext() { 124 while (iter.hasNext()) { 125 WeakObject weak = (WeakObject)iter.next(); 126 Object obj = null; 127 if (weak != null && (obj = weak.get()) == null) { 128 continue; 130 } 131 132 next = obj; 133 return true; 134 } 135 136 return false; 137 } 138 139 public Object next() { 140 if ((next == null) && !hasNext()) { 141 throw new NoSuchElementException (); 142 } 143 144 Object obj = next; 145 next = null; 146 147 return obj; 148 } 149 150 public void remove() { 151 iter.remove(); 152 } 153 }; 154 } 155 156 162 public boolean add(final Object obj) { 163 maintain(); 164 165 return set.add(WeakObject.create(obj, queue)); 166 } 167 168 173 public boolean isEmpty() { 174 maintain(); 175 176 return set.isEmpty(); 177 } 178 179 185 public boolean contains(final Object obj) { 186 maintain(); 187 188 return set.contains(WeakObject.create(obj)); 189 } 190 191 197 public boolean remove(final Object obj) { 198 maintain(); 199 200 return set.remove(WeakObject.create(obj)); 201 } 202 203 206 public void clear() { 207 set.clear(); 208 } 209 210 216 public Object clone() { 217 maintain(); 218 219 try { 220 return super.clone(); 221 } 222 catch (CloneNotSupportedException e) { 223 throw new InternalError (); 224 } 225 } 226 } 227 | Popular Tags |