package speiger.src.collections.PACKAGE.maps.impl.reference;

import java.util.Arrays;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.BiFunction;
import java.util.function.Predicate;
#if !TYPE_OBJECT && JDK_TYPE
import java.util.function.PREDICATE;
import java.util.OPTIONAL;
#endif
#if !SAME_TYPE && JDK_VALUE && !VALUE_OBJECT
import java.util.function.VALUE_PREDICATE;
import java.util.VALUE_OPTIONAL;
#endif

import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
#endif
import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER;
#if !TYPE_OBJECT && !VALUE_OBJECT
import speiger.src.collections.ints.functions.consumer.IntObjectConsumer;
#endif
#if !SAME_TYPE && !TYPE_INT
import speiger.src.collections.ints.functions.consumer.VALUE_BI_FROM_INT_CONSUMER;
#endif
#if !TYPE_OBJECT && !JDK_TYPE
import speiger.src.collections.PACKAGE.functions.OPTIONAL;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
#endif
#if !TYPE_INT || !SAME_TYPE
import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER;
#endif
import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR;
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
import speiger.src.collections.PACKAGE.maps.interfaces.MAP;
import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP;
import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET;
import speiger.src.collections.PACKAGE.sets.ORDERED_SET;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ORDERED_COLLECTION;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR;
#if !SAME_TYPE
import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR;
#endif
#if !VALUE_OBJECT && !SAME_TYPE
import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER;
import speiger.src.collections.VALUE_PACKAGE.lists.VALUE_LIST_ITERATOR;
#endif
#if !TYPE_OBJECT && !VALUE_OBJECT || !VALUE_OBJECT
import speiger.src.collections.objects.functions.consumer.ObjectObjectConsumer;
#endif
#if !SAME_TYPE
#if !TYPE_OBJECT
import speiger.src.collections.objects.functions.consumer.VALUE_BI_FROM_OBJECT_CONSUMER;

#endif
#if !JDK_VALUE
import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE;
import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_OPTIONAL;
#endif
#endif
#if !TYPE_OBJECT
#if !VALUE_OBJECT
import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator;

#endif
import speiger.src.collections.objects.collections.ObjectBidirectionalIterator;
import speiger.src.collections.objects.lists.ObjectListIterator;
import speiger.src.collections.objects.sets.AbstractObjectSet;
import speiger.src.collections.objects.sets.ObjectOrderedSet;
#endif
import speiger.src.collections.utils.HashUtil;

/**
 * A Type Specific LinkedHashMap implementation that uses specific arrays to create links between nodes to remove the wrapping of elements
 * to greatly reduce memory usage. In Addition adding some helper methods to move around elements.
 * This implementation of SortedMap does not support SubMaps of any kind. It implements the interface due to sortability and first/last access
 * @Type(T)
 * @ValueType(V)
 */
public class LINKED_REF_MAP KEY_VALUE_GENERIC_TYPE extends REF_MAP KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE
{
	/** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */
	protected transient long[] links;
	/** The First Index in the Map */
	protected int firstIndex = -1;
	/** The Last Index in the Map */
	protected int lastIndex = -1;
	
	/**
	 * Default Constructor
	 */
	public LINKED_REF_MAP() {
		this(HashUtil.DEFAULT_MIN_CAPACITY, HashUtil.DEFAULT_LOAD_FACTOR);
	}
	
	/**
	 * Constructor that defines the minimum capacity
	 * @param minCapacity the minimum capacity the HashMap is allowed to be.
	 * @throws IllegalStateException if the minimum capacity is negative
	 */
	public LINKED_REF_MAP(int minCapacity) {
		this(minCapacity, HashUtil.DEFAULT_LOAD_FACTOR);
	}
	
	/**
	 * Constructor that defines the minimum capacity and load factor
	 * @param minCapacity the minimum capacity the HashMap is allowed to be.
	 * @param loadFactor the percentage of how full the backing array can be before they resize
	 * @throws IllegalStateException if the minimum capacity is negative
	 * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
	 */
	public LINKED_REF_MAP(int minCapacity, float loadFactor) {
		super(minCapacity, loadFactor);
		links = new long[capacity + 1];
	}
	
#if !TYPE_OBJECT || !VALUE_OBJECT
	/**
	 * Helper constructor that allow to create a map from boxed values (it will unbox them)
	 * @param keys the keys that should be put into the map
	 * @param values the values that should be put into the map.
	 * @throws IllegalStateException if the keys and values do not match in lenght
	 */
	public LINKED_REF_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values) {
		this(keys, values, HashUtil.DEFAULT_LOAD_FACTOR);
	}
	
	/**
	 * Helper constructor that allow to create a map from boxed values (it will unbox them)
	 * @param keys the keys that should be put into the map
	 * @param values the values that should be put into the map.
	 * @param loadFactor the percentage of how full the backing array can be before they resize
	 * @throws IllegalStateException if the keys and values do not match in lenght
	 * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
	 */
	public LINKED_REF_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, float loadFactor) {
		this(keys.length, loadFactor);
		if(keys.length != values.length) throw new IllegalStateException("Input Arrays are not equal size");
		for(int i = 0,m=keys.length;i<m;i++) put(OBJ_TO_KEY(keys[i]), OBJ_TO_VALUE(values[i]));
	}
	
#endif
	/**
	 * Helper constructor that allow to create a map from unboxed values
	 * @param keys the keys that should be put into the map
	 * @param values the values that should be put into the map.
	 * @throws IllegalStateException if the keys and values do not match in lenght
	 */
	public LINKED_REF_MAP(KEY_TYPE[] keys, VALUE_TYPE[] values) {
		this(keys, values, HashUtil.DEFAULT_LOAD_FACTOR);
	}
	
	/**
	 * Helper constructor that allow to create a map from unboxed values
	 * @param keys the keys that should be put into the map
	 * @param values the values that should be put into the map.
	 * @param loadFactor the percentage of how full the backing array can be before they resize
	 * @throws IllegalStateException if the keys and values do not match in lenght
	 * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
	 */
	public LINKED_REF_MAP(KEY_TYPE[] keys, VALUE_TYPE[] values, float loadFactor) {
		this(keys.length, loadFactor);
		if(keys.length != values.length) throw new IllegalStateException("Input Arrays are not equal size");
		for(int i = 0,m=keys.length;i<m;i++) put(keys[i], values[i]);
	}
	
	/**
	 * A Helper constructor that allows to create a Map with exactly the same values as the provided map.
	 * @param map the values that should be present in the map
	 */
	public LINKED_REF_MAP(Map<? extends CLASS_TYPE, ? extends CLASS_VALUE_TYPE> map) {
		this(map, HashUtil.DEFAULT_LOAD_FACTOR);
	}
	
	/**
	 * A Helper constructor that allows to create a Map with exactly the same values as the provided map.
	 * @param map the values that should be present in the map
	 * @param loadFactor the percentage of how full the backing array can be before they resize
	 * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
	 */
	public LINKED_REF_MAP(Map<? extends CLASS_TYPE, ? extends CLASS_VALUE_TYPE> map, float loadFactor) {
		this(map.size(), loadFactor);
		putAll(map);
	}
	
	/**
	 * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map.
	 * @param map the values that should be present in the map
 	 */
	public LINKED_REF_MAP(MAP KEY_VALUE_GENERIC_TYPE map) {
		this(map, HashUtil.DEFAULT_LOAD_FACTOR);
	}
	
	/**
	 * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map.
	 * @param map the values that should be present in the map
	 * @param loadFactor the percentage of how full the backing array can be before they resize
	 * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
 	 */
	public LINKED_REF_MAP(MAP KEY_VALUE_GENERIC_TYPE map, float loadFactor) {
		this(map.size(), loadFactor);
		putAll(map);
	}
	
	@Override
	public VALUE_TYPE putAndMoveToFirst(KEY_TYPE key, VALUE_TYPE value) {
		Objects.requireNonNull(key);
		int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask;
		while(KEY_EQUALS_NOT_NULL(keys[pos])) {
			if(KEY_EQUALS(keys[pos].get(), key)) {
				VALUE_TYPE lastValue = values[pos];
				values[pos] = value;
				moveToFirstIndex(pos, false);
				return lastValue;
			}
			pos = ++pos & mask;
		}
		keys[pos] = new WeakKey<>(key, queue).index(pos);
		values[pos] = value;
		onNodeAdded(pos);
		moveToFirstIndex(pos, true);
		if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor));
		return getDefaultReturnValue();
	}
	
	@Override
	public VALUE_TYPE putAndMoveToLast(KEY_TYPE key, VALUE_TYPE value) {
		Objects.requireNonNull(key);
		int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask;
		while(KEY_EQUALS_NOT_NULL(keys[pos])) {
			if(KEY_EQUALS(keys[pos].get(), key)) {
				VALUE_TYPE lastValue = values[pos];
				values[pos] = value;
				moveToLastIndex(pos, false);
				return lastValue;
			}
			pos = ++pos & mask;
		}
		keys[pos] = new WeakKey<>(key, queue).index(pos);
		values[pos] = value;
		onNodeAdded(pos);
		moveToLastIndex(pos, true);
		
		if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor));
		return getDefaultReturnValue();
	}
	
	@Override
	public VALUE_TYPE putFirst(KEY_TYPE key, VALUE_TYPE value) {
		Objects.requireNonNull(key);
		int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask;
		while(KEY_EQUALS_NOT_NULL(keys[pos])) {
			if(KEY_EQUALS(keys[pos].get(), key)) return values[pos];
			pos = ++pos & mask;
		}
		keys[pos] = new WeakKey<>(key, queue).index(pos);
		values[pos] = value;
		onNodeAdded(pos);
		moveToFirstIndex(pos, true);
		
		if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor));
		return getDefaultReturnValue();
	}
	
	@Override
	public VALUE_TYPE putLast(KEY_TYPE key, VALUE_TYPE value) {
		Objects.requireNonNull(key);
		int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask;
		while(KEY_EQUALS_NOT_NULL(keys[pos])) {
			if(KEY_EQUALS(keys[pos].get(), key)) return values[pos];
			pos = ++pos & mask;
		}
		keys[pos] = new WeakKey<>(key, queue).index(pos);
		values[pos] = value;
		onNodeAdded(pos);
		moveToLastIndex(pos, true);
		
		if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor));
		return getDefaultReturnValue();
	}
	
	@Override
	public boolean moveToFirst(KEY_TYPE key) {
		Objects.requireNonNull(key);
		if(isEmpty() || KEY_EQUALS(FIRST_ENTRY_KEY(), key)) return false;
		int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask;
		while(KEY_EQUALS_NOT_NULL(keys[pos])) {
			if(KEY_EQUALS(keys[pos].get(), key)) {
				moveToFirstIndex(pos, false);
				return true;
			}
			pos = ++pos & mask;
		}
		return false;
	}
	
	@Override
	public boolean moveToLast(KEY_TYPE key) {
		Objects.requireNonNull(key);
		if(isEmpty() || KEY_EQUALS(LAST_ENTRY_KEY(), key)) return false;
		int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask;
		while(KEY_EQUALS_NOT_NULL(keys[pos])) {
			if(KEY_EQUALS(keys[pos].get(), key)) {
				moveToLastIndex(pos, false);
				return true;
			}
			pos = ++pos & mask;
		}
		return false;
	}
	
	@Override
	public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key) {
		int index = findIndex(key);
		if(index < 0) return getDefaultReturnValue();
		moveToFirstIndex(index, false);
		return values[index];
	}
	
	@Override
	public VALUE_TYPE getAndMoveToLast(KEY_TYPE key) {
		int index = findIndex(key);
		if(index < 0) return getDefaultReturnValue();
		moveToLastIndex(index, false);
		return values[index];
	}
	
#if !VALUE_OBJECT
	@Override
	public boolean containsValue(VALUE_TYPE value) {
		int index = firstIndex;
		while(index != -1) {
			if(VALUE_EQUALS(values[index], value)) return true;
			index = (int)links[index];
		}
		return false;
	}
	
#endif
	@Override
	@ValuePrimitive
	public boolean containsValue(Object value) {
		int index = firstIndex;
		while(index != -1) {
#if VALUE_OBJECT
			if(VALUE_EQUALS(values[index], value)) return true;
#else
			if((value == null && values[index] == getDefaultReturnValue()) || EQUALS_VALUE_TYPE(values[index], value)) return true;
#endif
			index = (int)links[index];
		}
		return false;
	}
	
	@Override
	public LINKED_REF_MAP KEY_VALUE_GENERIC_TYPE copy() {
		LINKED_REF_MAP KEY_VALUE_GENERIC_TYPE map = new LINKED_REF_MAPKV_BRACES(0, loadFactor);
		map.minCapacity = minCapacity;
		map.mask = mask;
		map.maxFill = maxFill;
		map.capacity = capacity;
		map.size = size;
		map.keys = new WeakKey[keys.length];
		for(int i = 0,m=keys.length;i<m;i++) {
			if(KEY_EQUALS_NOT_NULL(keys[i])) {
				map.keys[i] = new WeakKey<>(keys[i].get(), map.queue).index(i);
			}
		}
		map.values = Arrays.copyOf(values, values.length);
		map.links = Arrays.copyOf(links, links.length);
		map.firstIndex = firstIndex;
		map.lastIndex = lastIndex;
		return map;
	}
	
	@Override
	public KEY_TYPE FIRST_ENTRY_KEY() {
		if(size == 0) throw new NoSuchElementException();
		return keys[firstIndex].get();
	}
	
	@Override
	public KEY_TYPE POLL_FIRST_ENTRY_KEY() {
		if(size == 0) throw new NoSuchElementException();
		int pos = firstIndex;
		onNodeRemoved(pos);
		WeakKey<KEY_TYPE> result = keys[pos];
		size--;
		shiftKeys(pos);
		if(capacity > minCapacity && size < maxFill / 4 && capacity > HashUtil.DEFAULT_MIN_CAPACITY) rehash(capacity / 2);
		return result.get();
	}
	
	@Override
	public KEY_TYPE LAST_ENTRY_KEY() {
		if(size == 0) throw new NoSuchElementException();
		return keys[lastIndex].get();
	}
	
	@Override
	public KEY_TYPE POLL_LAST_ENTRY_KEY() {
		if(size == 0) throw new NoSuchElementException();
		int pos = lastIndex;
		onNodeRemoved(pos);
		WeakKey<KEY_TYPE> result = keys[pos];
		size--;
		shiftKeys(pos);
		if(capacity > minCapacity && size < maxFill / 4 && capacity > HashUtil.DEFAULT_MIN_CAPACITY) rehash(capacity / 2);
		return result.get();
	}
	
	@Override
	public VALUE_TYPE FIRST_ENTRY_VALUE() {
		if(size == 0) throw new NoSuchElementException();
		return values[firstIndex];
	}
	
	@Override
	public VALUE_TYPE LAST_ENTRY_VALUE() {
		if(size == 0) throw new NoSuchElementException();
		return values[lastIndex];
	}
	
	@Override
	public MAP.Entry KEY_VALUE_GENERIC_TYPE firstEntry() {
		if(size == 0) throw new NoSuchElementException();
		return new BasicEntryKV_BRACES(keys[firstIndex].get(), values[firstIndex]);
	}
	
	@Override
	public MAP.Entry KEY_VALUE_GENERIC_TYPE lastEntry() {
		if(size == 0) throw new NoSuchElementException();
		return new BasicEntryKV_BRACES(keys[lastIndex].get(), values[lastIndex]);
	}
	
	@Override
	public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirstEntry() {
		if(size == 0) throw new NoSuchElementException();
		int pos = firstIndex;
		onNodeRemoved(pos);
		BasicEntry KEY_VALUE_GENERIC_TYPE result = new BasicEntryKV_BRACES(keys[pos].get(), values[pos]);
		size--;
		shiftKeys(pos);
		if(capacity > minCapacity && size < maxFill / 4 && capacity > HashUtil.DEFAULT_MIN_CAPACITY) rehash(capacity / 2);
		return result;
	}
	
	@Override
	public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLastEntry() {
		if(size == 0) throw new NoSuchElementException();
		int pos = lastIndex;
		onNodeRemoved(pos);
		BasicEntry KEY_VALUE_GENERIC_TYPE result = new BasicEntryKV_BRACES(keys[pos].get(), values[pos]);
		size--;
		shiftKeys(pos);
		if(capacity > minCapacity && size < maxFill / 4 && capacity > HashUtil.DEFAULT_MIN_CAPACITY) rehash(capacity / 2);
		return result;
	}
	
	@Override
	public ObjectOrderedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> ENTRY_SET() {
		if(entrySet == null) entrySet = new MapEntrySet();
		return (ObjectOrderedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE>)entrySet;
	}
	
	@Override
	public ORDERED_SET KEY_GENERIC_TYPE keySet() {
		if(keySet == null) keySet = new KeySet();
		return (ORDERED_SET KEY_GENERIC_TYPE)keySet;
	}
	
	@Override
	public VALUE_ORDERED_COLLECTION VALUE_GENERIC_TYPE values() {
		if(valuesC == null) valuesC = new Values();
		return (VALUE_ORDERED_COLLECTION VALUE_GENERIC_TYPE)valuesC;
	}
	
	@Override
	public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) {
		int index = firstIndex;
		while(index != -1){
			action.accept(keys[index].get(), values[index]);
			index = (int)links[index];
		}
	}
	
	@Override
	public void clear() {
		super.clear();
		firstIndex = lastIndex = -1;
	}
	
	@Override
	public void clearAndTrim(int size) {
		int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor)));
		if(request >= capacity) {
			clear();
			return;
		}
		capacity = request;
		mask = request-1;
		maxFill = Math.min((int)Math.ceil(capacity * loadFactor), capacity - 1);
		for(int i = 0,m=keys.length;i<m;i++) {
			if(KEY_EQUALS_NOT_NULL(keys[i])) keys[i].index(-1);
		}
		keys = new WeakKey[request + 1];
		values = NEW_VALUE_ARRAY(request + 1);
		links = new long[request + 1];
		firstIndex = lastIndex = -1;
		this.size = 0;
	}
	
	protected void moveToFirstIndex(int startPos, boolean adding) {
		if(size == (adding ? 0 : 1) || firstIndex == startPos) return;
		if(lastIndex == startPos) {
			lastIndex = (int)(links[startPos] >>> 32);
			links[lastIndex] |= 0xFFFFFFFFL;
		}
		else {
			long link = links[startPos];
			int prev = (int)(link >>> 32);
			int next = (int)link;
			links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
			links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L);
		}
		links[firstIndex] ^= ((links[firstIndex] ^ ((startPos & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L);
		links[startPos] = 0xFFFFFFFF00000000L | (firstIndex & 0xFFFFFFFFL);
		firstIndex = startPos;
	}
	
	protected void moveToLastIndex(int startPos, boolean adding) {
		if(size == (adding ? 0 : 1) || lastIndex == startPos) return;
		if(firstIndex == startPos) {
			firstIndex = (int)links[startPos];
			links[lastIndex] |= 0xFFFFFFFF00000000L;
		}
		else {
			long link = links[startPos];
			int prev = (int)(link >>> 32);
			int next = (int)link;
			links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
			links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L);
		}
		links[lastIndex] ^= ((links[lastIndex] ^ (startPos & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
		links[startPos] = ((lastIndex & 0xFFFFFFFFL) << 32) | 0xFFFFFFFFL;
		lastIndex = startPos;
	}
	
	@Override
	protected void onNodeAdded(int pos) {
		if(size == 0) {
			firstIndex = lastIndex = pos;
			links[pos] = -1L;
		}
		else {
			links[lastIndex] ^= ((links[lastIndex] ^ (pos & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
			links[pos] = ((lastIndex & 0xFFFFFFFFL) << 32) | 0xFFFFFFFFL;
			lastIndex = pos;
		}
	}
	
	@Override
	protected void onNodeRemoved(int pos) {
		if(size == 0) firstIndex = lastIndex = -1;
		else if(firstIndex == pos) {
			firstIndex = (int)links[pos];
			if(0 <= firstIndex) links[firstIndex] |= 0xFFFFFFFF00000000L;
		}
		else if(lastIndex == pos) {
			lastIndex = (int)(links[pos] >>> 32);
			if(0 <= lastIndex) links[lastIndex] |= 0xFFFFFFFFL;
		}
		else {
			long link = links[pos];
			int prev = (int)(link >>> 32);
			int next = (int)link;
			links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
			links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L);
		}
	}
	
	@Override
	protected void onNodeMoved(int from, int to) {
		if(size == 1) {
			firstIndex = lastIndex = to;
			links[to] = -1L;
		}
		else if(firstIndex == from) {
			firstIndex = to;
			links[(int)links[from]] ^= ((links[(int)links[from]] ^ ((to & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L);
			links[to] = links[from];
		}
		else if(lastIndex == from) {
			lastIndex = to;
			links[(int)(links[from] >>> 32)] ^= ((links[(int)(links[from] >>> 32)] ^ (to & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
			links[to] = links[from];
		}
		else {
			long link = links[from];
			int prev = (int)(link >>> 32);
			int next = (int)link;
			links[prev] ^= ((links[prev] ^ (to & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
			links[next] ^= ((links[next] ^ ((to & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L);
			links[to] = link;
		}
	}
	
	@Override
	protected void rehash(int newSize) {
		int newMask = newSize - 1;
		WeakKey<KEY_TYPE>[] newKeys = new WeakKey[newSize + 1];
		VALUE_TYPE[] newValues = NEW_VALUE_ARRAY(newSize + 1);
		long[] newLinks = new long[newSize + 1];
		int i = firstIndex, prev = -1, newPrev = -1, pos;
		firstIndex = -1;
		for(int j = size; j-- != 0;) {
			if(KEY_EQUALS_NULL(keys[i])) pos = newSize;
			else {
				pos = HashUtil.mix(keys[i].hash()) & newMask;
				while(KEY_EQUALS_NOT_NULL(newKeys[pos])) pos = ++pos & newMask;
			}
			newKeys[pos] = keys[i].index(pos);
			newValues[pos] = values[i];
			if(prev != -1) {
				newLinks[newPrev] ^= ((newLinks[newPrev] ^ (pos & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
				newLinks[pos] ^= ((newLinks[pos] ^ ((newPrev & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L);
				newPrev = pos;
			}
			else {
				newPrev = firstIndex = pos;
				newLinks[pos] = -1L;
			}
			i = (int)links[prev = i];
		}
		links = newLinks;
		lastIndex = newPrev;
		if(newPrev != -1) newLinks[newPrev] |= 0xFFFFFFFFL;
		capacity = newSize;
		mask = newMask;
		maxFill = Math.min((int)Math.ceil(capacity * loadFactor), capacity - 1);
		keys = newKeys;
		values = newValues;
	}
	
	private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE {
		@Override
		public void addFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
		@Override
		public void addLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
		@Override
		public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
		@Override
		public boolean addAndMoveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
		
		@Override
		public boolean moveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) {
			return LINKED_REF_MAP.this.moveToFirst(o.ENTRY_KEY());
		}
		
		@Override
		public boolean moveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) {
			return LINKED_REF_MAP.this.moveToLast(o.ENTRY_KEY());
		}
		
		@Override
		public MAP.Entry KEY_VALUE_GENERIC_TYPE getFirst() {
			return new BasicEntryKV_BRACES(FIRST_ENTRY_KEY(), FIRST_ENTRY_VALUE());
		}
		
		@Override
		public MAP.Entry KEY_VALUE_GENERIC_TYPE getLast() {
			return new BasicEntryKV_BRACES(LAST_ENTRY_KEY(), LAST_ENTRY_VALUE());
		}
		
		@Override
		public MAP.Entry KEY_VALUE_GENERIC_TYPE removeFirst() {
			BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(FIRST_ENTRY_KEY(), FIRST_ENTRY_VALUE());
			POLL_FIRST_ENTRY_KEY();
			return entry;
		}
		
		@Override
		public MAP.Entry KEY_VALUE_GENERIC_TYPE removeLast() {
			BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(LAST_ENTRY_KEY(), LAST_ENTRY_VALUE());
			POLL_LAST_ENTRY_KEY();
			return entry;
		}
		
		@Override
		public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> iterator() {
			return new EntryIterator(true);
		}
		
		@Override
		public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> reverseIterator() {
			return new EntryIterator(false);
		}
		
		@Override
		public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> iterator(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement) {
			return new EntryIterator(fromElement.ENTRY_KEY());
		}
		
		@Override
		public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> fastIterator() {
			return new FastEntryIterator(true);
		}
		
		@Override
		public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> fastIterator(KEY_TYPE fromElement) {
			return new FastEntryIterator(fromElement);
		}
		
		@Override
		public MapEntrySet copy() { throw new UnsupportedOperationException(); }
		
		@Override
		public void forEach(Consumer<? super MAP.Entry KEY_VALUE_GENERIC_TYPE> action) {
			int index = firstIndex;
			while(index != -1){
				action.accept(new ValueMapEntry(index));
				index = (int)links[index];
			}
		}
		
		@Override
		public void fastForEach(Consumer<? super MAP.Entry KEY_VALUE_GENERIC_TYPE> action) {
			MapEntry entry = new MapEntry();
			int index = firstIndex;
			while(index != -1){
				entry.set(index);
				action.accept(entry);
				index = (int)links[index];
			}
		}
		
		@Override
		public void forEachIndexed(IntObjectConsumer<MAP.Entry KEY_VALUE_GENERIC_TYPE> action) {
			Objects.requireNonNull(action);
			if(size() <= 0) return;
			int count = 0;
			int index = firstIndex;
			while(index != -1) {
				action.accept(count++, new ValueMapEntry(index));
				index = (int)links[index];
			}
		}
		
		@Override
		public <E> void forEach(E input, ObjectObjectConsumer<E, MAP.Entry KEY_VALUE_GENERIC_TYPE> action) {
			Objects.requireNonNull(action);
			if(size() <= 0) return;
			int index = firstIndex;
			while(index != -1) {
				action.accept(input, new ValueMapEntry(index));
				index = (int)links[index];
			}
		}
		
		@Override
		public boolean matchesAny(Predicate<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
			Objects.requireNonNull(filter);
			if(size() <= 0) return false;
			MapEntry entry = new MapEntry();
			int index = firstIndex;
			while(index != -1) {
				entry.set(index);
				if(filter.test(entry)) return true;
				index = (int)links[index];
			}
			return false;
		}
		
		@Override
		public boolean matchesNone(Predicate<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
			Objects.requireNonNull(filter);
			if(size() <= 0) return true;
			MapEntry entry = new MapEntry();
			int index = firstIndex;
			while(index != -1) {
				entry.set(index);
				if(filter.test(entry)) return false;
				index = (int)links[index];
			}
			return true;
		}
		
		@Override
		public boolean matchesAll(Predicate<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
			Objects.requireNonNull(filter);
			if(size() <= 0) return true;
			MapEntry entry = new MapEntry();
			int index = firstIndex;
			while(index != -1) {
				entry.set(index);
				if(!filter.test(entry)) return false;
				index = (int)links[index];
			}
			return true;
		}
		
		@Override
		public <E> E reduce(E identity, BiFunction<E, MAP.Entry KEY_VALUE_GENERIC_TYPE, E> operator) {
			Objects.requireNonNull(operator);
			E state = identity;
			int index = firstIndex;
			while(index != -1) {
				state = operator.apply(state, new ValueMapEntry(index));
				index = (int)links[index];
			}
			return state;
		}
		
		@Override
		public Optional<MAP.Entry KEY_VALUE_GENERIC_TYPE> reduce(ObjectObjectUnaryOperator<MAP.Entry KEY_VALUE_GENERIC_TYPE, MAP.Entry KEY_VALUE_GENERIC_TYPE> operator) {
			Objects.requireNonNull(operator);
			MAP.Entry KEY_VALUE_GENERIC_TYPE state = null;
			boolean empty = true;
			int index = firstIndex;
			while(index != -1) {
				if(empty) {
					empty = false;
					state = new ValueMapEntry(index);
					index = (int)links[index];
					continue;
				}
				state = operator.apply(state, new ValueMapEntry(index));
				index = (int)links[index];
			}
			return empty ? Optional.empty() : Optional.ofNullable(state);
		}
		
		@Override
		public Optional<MAP.Entry KEY_VALUE_GENERIC_TYPE> findFirst(Predicate<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
			Objects.requireNonNull(filter);
			if(size() <= 0) return Optional.empty();
			MapEntry entry = new MapEntry();
			int index = firstIndex;
			while(index != -1) {
				entry.set(index);
				if(filter.test(entry)) return Optional.ofNullable(entry);
				index = (int)links[index];
			}
			return Optional.empty();
		}
		
		@Override
		public int count(Predicate<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
			Objects.requireNonNull(filter);
			if(size() <= 0) return 0;
			int result = 0;
			MapEntry entry = new MapEntry();
			int index = firstIndex;
			while(index != -1) {
				entry.set(index);
				if(filter.test(entry)) result++;
				index = (int)links[index];
			}
			return result;
		}
		
		@Override
		@Deprecated
		public boolean contains(Object o) {
			if(o instanceof Map.Entry) {
				if(o instanceof MAP.Entry) {
					MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o;
					int index = LINKED_REF_MAP.this.findIndex(entry.ENTRY_KEY());
					if(index >= 0) return VALUE_EQUALS(entry.ENTRY_VALUE(), LINKED_REF_MAP.this.values[index]);
				}
				else {
					Map.Entry<?, ?> entry = (Map.Entry<?, ?>)o;
					int index = LINKED_REF_MAP.this.findIndex(entry.getKey());
					if(index >= 0) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(LINKED_REF_MAP.this.values[index]));
				}
			}
			return false;
		}
		
		@Override
		@Deprecated
		public boolean remove(Object o) {
			if(o instanceof Map.Entry) {
				if(o instanceof MAP.Entry) {
					MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o;
					return LINKED_REF_MAP.this.remove(entry.ENTRY_KEY(), entry.ENTRY_VALUE());
				}
				Map.Entry<?, ?> entry = (Map.Entry<?, ?>)o;
				return LINKED_REF_MAP.this.remove(entry.getKey(), entry.getValue());
			}
			return false;
		}
		
		@Override
		public int size() {
			return LINKED_REF_MAP.this.size();
		}
		
		@Override
		public void clear() {
			LINKED_REF_MAP.this.clear();
		}
	}
	
	private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE {
#if TYPE_OBJECT
		@Override
		@Deprecated
		public boolean contains(Object e) {
			return containsKey(e);
		}
		
		@Override
		public boolean remove(Object o) {
			int oldSize = size;
			LINKED_REF_MAP.this.remove(o);
			return size != oldSize;
		}
		
#else
		@Override
		public boolean contains(KEY_TYPE e) {
			return containsKey(e);
		}
		
		@Override
		public boolean remove(KEY_TYPE o) {
			int oldSize = size;
			LINKED_REF_MAP.this.remove(o);
			return size != oldSize;
		}
		
#endif
		@Override
		public boolean add(KEY_TYPE o) { throw new UnsupportedOperationException(); }

		@Override
		public void addFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
		
		@Override
		public void addLast(KEY_TYPE o) { throw new UnsupportedOperationException(); }
		
		@Override
		public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }

		@Override
		public boolean addAndMoveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); }

		@Override
		public boolean moveToFirst(KEY_TYPE o) {
			return LINKED_REF_MAP.this.moveToFirst(o);
		}

		@Override
		public boolean moveToLast(KEY_TYPE o) {
			return LINKED_REF_MAP.this.moveToLast(o);
		}
		
		@Override
		public LIST_ITERATOR KEY_GENERIC_TYPE iterator() {
			return new KeyIterator(true);
		}
		
		@Override
		public LIST_ITERATOR KEY_GENERIC_TYPE reverseIterator() {
			return new KeyIterator(false);
		}
		
		@Override
		public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) {
			return new KeyIterator(fromElement);
		}
		
		@Override
		public KeySet copy() { throw new UnsupportedOperationException(); }
		
		@Override
		public int size() {
			return LINKED_REF_MAP.this.size();
		}
		
		@Override
		public void clear() {
			LINKED_REF_MAP.this.clear();
		}
		
		@Override
		public KEY_TYPE GET_FIRST_KEY() {
			return FIRST_ENTRY_KEY();
		}
		
		@Override
		public KEY_TYPE REMOVE_FIRST_KEY() {
			return POLL_FIRST_ENTRY_KEY();
		}

		@Override
		public KEY_TYPE GET_LAST_KEY() {
			return LAST_ENTRY_KEY();
		}

		@Override
		public KEY_TYPE REMOVE_LAST_KEY() {
			return POLL_LAST_ENTRY_KEY();
		}
		
		@Override
		public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
			int index = firstIndex;
			while(index != -1){
				action.accept(keys[index].get());
				index = (int)links[index];
			}
		}
		
		@Override
		public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) {
			Objects.requireNonNull(action);
			if(size() <= 0) return;
			int count = 0;
			int index = firstIndex;
			while(index != -1){
				action.accept(count++, keys[index].get());
				index = (int)links[index];
			}
		}
		
		@Override
		public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
			Objects.requireNonNull(action);
			if(size() <= 0) return;
			int index = firstIndex;
			while(index != -1) {
				action.accept(input, keys[index].get());
				index = (int)links[index];
			}
		}
		
		@Override
		public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
			Objects.requireNonNull(filter);
			if(size() <= 0) return false;
			int index = firstIndex;
			while(index != -1) {
				if(filter.test(keys[index].get())) return true;
				index = (int)links[index];
			}
			return false;
		}
		
		@Override
		public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
			Objects.requireNonNull(filter);
			if(size() <= 0) return true;
			int index = firstIndex;
			while(index != -1) {
				if(filter.test(keys[index].get())) return false;
				index = (int)links[index];
			}
			return true;
		}
		
		@Override
		public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
			Objects.requireNonNull(filter);
			if(size() <= 0) return true;
			int index = firstIndex;
			while(index != -1) {
				if(!filter.test(keys[index].get())) return false;
				index = (int)links[index];
			}
			return true;
		}
		
#if !TYPE_OBJECT
		@Override
		public KEY_TYPE reduce(KEY_TYPE identity, SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
			Objects.requireNonNull(operator);
			KEY_TYPE state = identity;
			int index = firstIndex;
			while(index != -1) {
				state = operator.APPLY_KEY_VALUE(state, keys[index].get());
				index = (int)links[index];
			}
			return state;
		}
		
#else
		@Override
		public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
			Objects.requireNonNull(operator);
			KEY_SPECIAL_TYPE state = identity;
			int index = firstIndex;
			while(index != -1) {
				state = operator.apply(state, keys[index].get());
				index = (int)links[index];
			}
			return state;
		}
		
#endif
		@Override
		public OPTIONAL KEY_GENERIC_TYPE reduce(SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
			Objects.requireNonNull(operator);
			KEY_TYPE state = EMPTY_KEY_VALUE;
			boolean empty = true;
			int index = firstIndex;
			while(index != -1) {
				if(empty) {
					empty = false;
					state = keys[index].get();
					index = (int)links[index];
					continue;
				}
				state = operator.APPLY_KEY_VALUE(state, keys[index].get());
				index = (int)links[index];
			}
			return empty ? OPTIONAL.empty() : OPTIONAL.GET_OPTIONAL(state);
		}
		
		@Override
		public OPTIONAL KEY_GENERIC_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
			Objects.requireNonNull(filter);
			if(size() <= 0) return OPTIONAL.empty();
			int index = firstIndex;
			while(index != -1){
				if(filter.test(keys[index].get())) return OPTIONAL.GET_OPTIONAL(keys[index].get());
				index = (int)links[index];
			}
			return OPTIONAL.empty();
		}
		
		@Override
		public int count(PREDICATE KEY_GENERIC_TYPE filter) {
			Objects.requireNonNull(filter);
			if(size() <= 0) return 0;
			int result = 0;
			int index = firstIndex;
			while(index != -1){
				if(filter.test(keys[index].get())) result++;
				index = (int)links[index];
			}
			return result;
		}
	}
	
	private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE implements VALUE_ORDERED_COLLECTION VALUE_GENERIC_TYPE {
#if VALUE_OBJECT
		@Override
		@Deprecated
		public boolean contains(Object e) { return containsValue(e); }
		
#else
		@Override
		public boolean contains(VALUE_TYPE e) { return containsValue(e); }
		
#endif
		@Override
		public boolean add(VALUE_TYPE o) { throw new UnsupportedOperationException(); }
		@Override
		public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() { return new ValueIterator(true); }
		@Override
		public int size() { return LINKED_REF_MAP.this.size(); }
		@Override
		public void clear() { LINKED_REF_MAP.this.clear(); }
		@Override
		public VALUE_ORDERED_COLLECTION VALUE_GENERIC_TYPE reversed() { return new VALUE_ABSTRACT_COLLECTION.VALUE_REVERSED_ORDERED_COLLECTIONVALUE_BRACES(this, this::reverseIterator); }
		private VALUE_ITERATOR VALUE_GENERIC_TYPE reverseIterator() {
			return new ValueIterator(false);
		}
		@Override
		public void addFirst(VALUE_TYPE e) { throw new UnsupportedOperationException(); }
		@Override
		public void addLast(VALUE_TYPE e) { throw new UnsupportedOperationException(); }
		@Override
		public VALUE_TYPE VALUE_GET_FIRST_KEY() { return FIRST_ENTRY_VALUE(); }
		@Override
		public VALUE_TYPE VALUE_REMOVE_FIRST_KEY() {
			VALUE_TYPE result = FIRST_ENTRY_VALUE();
			POLL_FIRST_ENTRY_KEY();
			return result; 
		}
		@Override
		public VALUE_TYPE VALUE_GET_LAST_KEY() { return LAST_ENTRY_VALUE(); }
		@Override
		public VALUE_TYPE VALUE_REMOVE_LAST_KEY() {
			VALUE_TYPE result = LAST_ENTRY_VALUE();
			POLL_LAST_ENTRY_KEY();
			return result; 
		}
		@Override
		public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) {
			Objects.requireNonNull(action);
			int index = firstIndex;
			while(index != -1){
				action.accept(values[index]);
				index = (int)links[index];
			}
		}
		
		@Override
		public void forEachIndexed(VALUE_BI_FROM_INT_CONSUMER VALUE_GENERIC_TYPE action) {
			Objects.requireNonNull(action);
			if(size() <= 0) return;
			int count = 0;
			int index = firstIndex;
			while(index != -1){
				action.accept(count++, values[index]);
				index = (int)links[index];
			}
		}
		
		@Override
		public <E> void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE<E> action) {
			Objects.requireNonNull(action);
			if(size() <= 0) return;
			int index = firstIndex;
			while(index != -1){
				action.accept(input, values[index]);
				index = (int)links[index];
			}
		}
		
		@Override
		public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
			Objects.requireNonNull(filter);
			if(size() <= 0) return false;
			int index = firstIndex;
			while(index != -1){
				if(filter.test(values[index])) return true;
				index = (int)links[index];
			}
			return false;
		}
		
		@Override
		public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
			Objects.requireNonNull(filter);
			if(size() <= 0) return true;
			int index = firstIndex;
			while(index != -1) {
				if(filter.test(values[index])) return false;
				index = (int)links[index];
			}
			return true;
		}
		
		@Override
		public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
			Objects.requireNonNull(filter);
			if(size() <= 0) return true;
			int index = firstIndex;
			while(index != -1) {
				if(!filter.test(values[index])) return false;
				index = (int)links[index];
			}
			return true;
		}
		
#if !VALUE_OBJECT
		@Override
		public VALUE_TYPE reduce(VALUE_TYPE identity, VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) {
			Objects.requireNonNull(operator);
			VALUE_TYPE state = identity;
			int index = firstIndex;
			while(index != -1) {
				state = operator.APPLY_VALUE(state, values[index]);
				index = (int)links[index];
			}
			return state;
		}
		
#else
		@Override
		public <VALUE_SPECIAL_TYPE> VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction<VALUE_SPECIAL_TYPE, VALUE_TYPE, VALUE_SPECIAL_TYPE> operator) {
			Objects.requireNonNull(operator);
			VALUE_SPECIAL_TYPE state = identity;
			int index = firstIndex;
			while(index != -1) {
				state = operator.apply(state, values[index]);
				index = (int)links[index];
			}
			return state;
		}
		
#endif
		@Override
		public VALUE_OPTIONAL VALUE_GENERIC_TYPE reduce(VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) {
			Objects.requireNonNull(operator);
			VALUE_TYPE state = EMPTY_VALUE;
			boolean empty = true;
			int index = firstIndex;
			while(index != -1) {
				if(empty) {
					empty = false;
					state = values[index];
					index = (int)links[index];
					continue;
				}
				state = operator.APPLY_VALUE(state, values[index]);
				index = (int)links[index];
			}
			return empty ? VALUE_OPTIONAL.empty() : VALUE_OPTIONAL.GET_OPTIONAL_VALUE(state);
		}
		
		@Override
		public VALUE_OPTIONAL VALUE_GENERIC_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
			Objects.requireNonNull(filter);
			if(size() <= 0) return VALUE_OPTIONAL.empty();
			int index = firstIndex;
			while(index != -1){
				if(filter.test(values[index])) return VALUE_OPTIONAL.GET_OPTIONAL_VALUE(values[index]);
				index = (int)links[index];
			}
			return VALUE_OPTIONAL.empty();
		}
		
		@Override
		public int count(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
			Objects.requireNonNull(filter);
			if(size() <= 0) return 0;
			int result = 0;
			int index = firstIndex;
			while(index != -1){
				if(filter.test(values[index])) result++;
				index = (int)links[index];
			}
			return result;
		}
	}
	
	private class FastEntryIterator extends MapIterator implements ObjectListIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
		MapEntry entry = new MapEntry();
		
		public FastEntryIterator(boolean start) { super(start); }
		public FastEntryIterator(KEY_TYPE from) {
			super(from);
		}
		
		@Override
		public MAP.Entry KEY_VALUE_GENERIC_TYPE next() {
			entry.index = nextEntry();
			return entry;
		}
		
		@Override
		public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() {
			entry.index = previousEntry();
			return entry;
		}
		
		@Override
		public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); }

		@Override
		public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); }
	}
	
	private class EntryIterator extends MapIterator implements ObjectListIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
		MapEntry entry;
		
		public EntryIterator(boolean start) { super(start); }
		public EntryIterator(KEY_TYPE from) {
			super(from);
		}
		
		@Override
		public MAP.Entry KEY_VALUE_GENERIC_TYPE next() {
			return entry = new ValueMapEntry(nextEntry());
		}
		
		@Override
		public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() {
			return entry = new ValueMapEntry(previousEntry());
		}
		
		@Override
		public void remove() {
			super.remove();
			entry.index = -1;
		}

		@Override
		public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); }

		@Override
		public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); }
	}
	
	private class KeyIterator extends MapIterator implements LIST_ITERATOR KEY_GENERIC_TYPE {
		
		public KeyIterator(boolean start) { super(start); }
		public KeyIterator(KEY_TYPE from) {
			super(from);
		}
		
		@Override
		public KEY_TYPE PREVIOUS() {
			return keys[previousEntry()].get();
		}

		@Override
		public KEY_TYPE NEXT() {
			return keys[nextEntry()].get();
		}
		
		@Override
		public void set(KEY_TYPE e) { throw new UnsupportedOperationException(); }
		@Override
		public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); }
	}
	
	private class ValueIterator extends MapIterator implements VALUE_LIST_ITERATOR VALUE_GENERIC_TYPE {
		public ValueIterator(boolean start) { super(start); }
		
		@Override
		public VALUE_TYPE VALUE_PREVIOUS() {
			return values[previousEntry()];
		}

		@Override
		public VALUE_TYPE VALUE_NEXT() {
			return values[nextEntry()];
		}

		@Override
		public void set(VALUE_TYPE e) { throw new UnsupportedOperationException(); }

		@Override
		public void add(VALUE_TYPE e) { throw new UnsupportedOperationException(); }
	}
	
	private class MapIterator {
		boolean forward;
		int previous = -1;
		int next = -1;
		int current = -1;
		int index = 0;
		
		MapIterator(boolean start) {
			this.forward = start;
			if(start) next = firstIndex;
			else previous = lastIndex;
		}
		
		MapIterator(KEY_TYPE from) {
			Objects.requireNonNull(from);
			if(keys[lastIndex] == from) {
				previous = lastIndex;
				index = size;
			}
			else {
				int pos = HashUtil.mix(KEY_TO_HASH(from)) & mask;
				WeakKey<KEY_TYPE> refKey = null;
				while(KEY_EQUALS_NOT_NULL((refKey = keys[pos]))) {
					if(KEY_EQUALS(refKey.get(), from)) {
						next = (int)links[pos];
						previous = pos;
						break;
					}
					pos = ++pos & mask;
				}
				if(previous == -1 && next == -1)
					throw new NoSuchElementException("The element was not found");
			}
		}
		
		public boolean hasNext() {
			return (forward ? next : previous) != -1;
		}

		public boolean hasPrevious() {
			return (forward ? previous : next) != -1;
		}
		
		public int nextIndex() {
			ensureIndexKnown();
			return index;
		}
		
		public int previousIndex() {
			ensureIndexKnown();
			return index - 1;
		}
		
		public void remove() {
			if(current == -1) throw new IllegalStateException();
			ensureIndexKnown();
			if(current == previous) {
				index--;
				previous = (int)(links[current] >>> 32);
			}
			else next = (int)links[current];
			size--;
			if(previous == -1) firstIndex = next;
			else links[previous] ^= ((links[previous] ^ (next & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
			
			if(next == -1) lastIndex = previous;
			else links[next] ^= ((links[next] ^ ((previous & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L);
			if(current == capacity) {
				current = -1;
				keys[capacity] = EMPTY_KEY_VALUE;
				values[capacity] = EMPTY_VALUE;
			}
			else {
				int slot, last, startPos = current;
				current = -1;
				WeakKey<KEY_TYPE> current;
				while(true) {
					startPos = ((last = startPos) + 1) & mask;
					while(true){
						if(KEY_EQUALS_NULL((current = keys[startPos]))) {
							keys[last] = EMPTY_KEY_VALUE;
							values[last] = EMPTY_VALUE;
							return;
						}
						slot = HashUtil.mix(current.hash()) & mask;
						if(last <= startPos ? (last >= slot || slot > startPos) : (last >= slot && slot > startPos)) break;
						startPos = ++startPos & mask;
					}
					keys[last] = current.index(last);
					values[last] = values[startPos];
					if(next == startPos) next = last;
					if(previous == startPos) previous = last;
					onNodeMoved(startPos, last);
				}
			}
		}
		
		public int previousEntry() {
			if(!hasPrevious()) throw new NoSuchElementException();
			if(forward) moveBackwards();
			else moveForwards();
			if(index >= 0) index--;
			return current;
		}
		
		public int nextEntry() {
			if(!hasNext()) throw new NoSuchElementException();
			if(forward) moveForwards();
			else moveBackwards();
			if(index >= 0) index++;
			return current;
		}
		
		private void moveBackwards() {
			current = previous;
			previous = (int)(links[current] >> 32);
			next = current;
		}
		
		private void moveForwards() {
			current = next;
			next = (int)(links[current]);
			previous = current;
		}
		
		private void ensureIndexKnown() {
			if(index == -1) {
				if(previous == -1) {
					index = 0;
				}
				else if(next == -1) {
					index = size;
				}
				else {
					index = 1;
					for(int pos = firstIndex;pos != previous;pos = (int)links[pos], index++);
				}
			}
		}

	}
}