-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
LinkedHashSetTempSetNoClear.java
59 lines (50 loc) · 1.54 KB
/
LinkedHashSetTempSetNoClear.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package nallar.collections;
import nallar.tickthreading.Log;
import java.util.Iterator;
import java.util.LinkedHashSet;
public class LinkedHashSetTempSetNoClear<T> extends LinkedHashSet<T> {
private boolean iterating = false;
private final LinkedHashSet<T> toAdd = new LinkedHashSet<T>();
private final LinkedHashSet<Object> toRemove = new LinkedHashSet<Object>();
@Override
public synchronized boolean add(final T t) {
if (iterating) {
boolean contains = super.contains(t);
return (toRemove.remove(t) && contains) || (!contains && toAdd.add(t));
}
return super.add(t);
}
@Override
public synchronized boolean remove(final Object o) {
if (iterating) {
return super.contains(o) && toRemove.add(o) || toAdd.remove(o);
}
return super.remove(o);
}
@Override
public synchronized boolean contains(final Object o) {
return iterating ? super.contains(o) && !toRemove.contains(o) || toAdd.contains(o) : super.contains(o);
}
@Override
public int size() {
return iterating ? super.size() + toAdd.size() - toRemove.size() : super.size();
}
public synchronized Iterator<T> startIteration() {
if (iterating) {
Log.severe("Started iterating when not previously done", new Throwable());
done();
}
iterating = true;
return super.iterator();
}
public synchronized void done() {
if (!iterating) {
throw new IllegalStateException("Not iterating yet.");
}
iterating = false;
super.addAll(toAdd);
super.removeAll(toRemove);
toAdd.clear();
toRemove.clear();
}
}