package me.nallar.collections;

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) {
			throw new IllegalStateException("Already iterating.");
		}
		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();
	}

	public boolean isIterating() {
		return iterating;
	}
}

@@ -90,16 +90,55 @@
 Set;%0D%0A%0D%0A
+import me.nallar.tickthreading.Log;%0D%0A%0D%0A
 public c
@@ -1194,60 +1194,92 @@
 %0A%09%09%09
-throw new IllegalStateException(%22Already iterating.%22
+Log.severe(%22Started iterating when not previously done%22, new Throwable());%0D%0A%09%09%09done(
 );%0D%0A
@@ -1581,68 +1581,8 @@
 %0A%09%7D%0D
-%0A%0D%0A%09public boolean isIterating() %7B%0D%0A%09%09return iterating;%0D%0A%09%7D%0D
 %0A%7D%0D%0A

Fix #625