Unnamed: 0
int64 0
2.1k
| func
stringlengths 30
107k
| target
bool 2
classes | project
stringlengths 62
145
|
---|---|---|---|
0 | public abstract class AbstractEntryIterator<K, V, T> implements OLazyIterator<T>, OResettable {
OMVRBTree<K, V> tree;
OMVRBTreeEntry<K, V> begin;
OMVRBTreeEntry<K, V> next;
OMVRBTreeEntry<K, V> lastReturned;
int expectedModCount;
int pageIndex;
AbstractEntryIterator(final OMVRBTreeEntry<K, V> start) {
begin = start;
init();
}
private void init() {
if (begin == null)
// IN CASE OF ABSTRACTMAP.HASHCODE()
return;
tree = begin.getTree();
next = begin;
expectedModCount = tree.modCount;
lastReturned = null;
pageIndex = begin.getTree().getPageIndex() > -1 ? begin.getTree().getPageIndex() - 1 : -1;
}
@Override
public void reset() {
init();
}
public boolean hasNext() {
if (tree != null && expectedModCount != tree.modCount) {
// CONCURRENT CHANGE: TRY TO REUSE LAST POSITION
pageIndex--;
expectedModCount = tree.modCount;
}
return next != null && (pageIndex < next.getSize() - 1 || OMVRBTree.successor(next) != null);
}
public final boolean hasPrevious() {
if (tree != null && expectedModCount != tree.modCount) {
// CONCURRENT CHANGE: TRY TO REUSE LAST POSITION
pageIndex = -1;
expectedModCount = tree.modCount;
}
return next != null && (pageIndex > 0 || OMVRBTree.predecessor(next) != null);
}
final K nextKey() {
return nextEntry().getKey(pageIndex);
}
final V nextValue() {
return nextEntry().getValue(pageIndex);
}
final V prevValue() {
return prevEntry().getValue(pageIndex);
}
final OMVRBTreeEntry<K, V> nextEntry() {
if (next == null)
throw new NoSuchElementException();
if (pageIndex < next.getSize() - 1) {
// ITERATE INSIDE THE NODE
pageIndex++;
} else {
// GET THE NEXT NODE
if (tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
next = OMVRBTree.successor(next);
pageIndex = 0;
}
lastReturned = next;
tree.pageIndex = pageIndex;
return next;
}
final OMVRBTreeEntry<K, V> prevEntry() {
if (next == null)
throw new NoSuchElementException();
if (pageIndex > 0) {
// ITERATE INSIDE THE NODE
pageIndex--;
} else {
if (tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
next = OMVRBTree.predecessor(next);
pageIndex = next != null ? next.getSize() - 1 : -1;
}
lastReturned = next;
return next;
}
@SuppressWarnings("unchecked")
public T update(final T iValue) {
if (lastReturned == null)
throw new IllegalStateException();
if (tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
tree.pageIndex = pageIndex;
return (T) next.setValue((V) iValue);
}
public void remove() {
if (lastReturned == null)
throw new IllegalStateException();
if (tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
// deleted entries are replaced by their successors
if (lastReturned.getLeft() != null && lastReturned.getRight() != null)
next = lastReturned;
tree.pageIndex = pageIndex;
next = tree.deleteEntry(lastReturned);
pageIndex--;
expectedModCount = tree.modCount;
lastReturned = null;
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_AbstractEntryIterator.java |
1 | public final class OAlwaysGreaterKey implements Comparable<Comparable<?>>{
public int compareTo(Comparable<?> o) {
return 1;
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OAlwaysGreaterKey.java |
2 | public final class OAlwaysLessKey implements Comparable<Comparable<?>> {
public int compareTo(Comparable<?> o) {
return -1;
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OAlwaysLessKey.java |
3 | public class OCompositeKey implements Comparable<OCompositeKey>, Serializable {
private static final long serialVersionUID = 1L;
/**
* List of heterogeneous values that are going to be stored in {@link OMVRBTree}.
*/
private final List<Object> keys;
private final Comparator<Object> comparator;
public OCompositeKey(final List<?> keys) {
this.keys = new ArrayList<Object>(keys.size());
this.comparator = ODefaultComparator.INSTANCE;
for (final Object key : keys)
addKey(key);
}
public OCompositeKey(final Object... keys) {
this.keys = new ArrayList<Object>(keys.length);
this.comparator = ODefaultComparator.INSTANCE;
for (final Object key : keys)
addKey(key);
}
public OCompositeKey() {
this.keys = new ArrayList<Object>();
this.comparator = ODefaultComparator.INSTANCE;
}
/**
* Clears the keys array for reuse of the object
*/
public void reset() {
if (this.keys != null)
this.keys.clear();
}
/**
* @return List of heterogeneous values that are going to be stored in {@link OMVRBTree}.
*/
public List<Object> getKeys() {
return Collections.unmodifiableList(keys);
}
/**
* Add new key value to the list of already registered values.
*
* If passed in value is {@link OCompositeKey} itself then its values will be copied in current index. But key itself will not be
* added.
*
* @param key
* Key to add.
*/
public void addKey(final Object key) {
if (key instanceof OCompositeKey) {
final OCompositeKey compositeKey = (OCompositeKey) key;
for (final Object inKey : compositeKey.keys) {
addKey(inKey);
}
} else {
keys.add(key);
}
}
/**
* Performs partial comparison of two composite keys.
*
* Two objects will be equal if the common subset of their keys is equal. For example if first object contains two keys and second
* contains four keys then only first two keys will be compared.
*
* @param otherKey
* Key to compare.
*
* @return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified
* object.
*/
public int compareTo(final OCompositeKey otherKey) {
final Iterator<Object> inIter = keys.iterator();
final Iterator<Object> outIter = otherKey.keys.iterator();
while (inIter.hasNext() && outIter.hasNext()) {
final Object inKey = inIter.next();
final Object outKey = outIter.next();
if (outKey instanceof OAlwaysGreaterKey)
return -1;
if (outKey instanceof OAlwaysLessKey)
return 1;
final int result = comparator.compare(inKey, outKey);
if (result != 0)
return result;
}
return 0;
}
/**
* {@inheritDoc }
*/
@Override
public boolean equals(final Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
final OCompositeKey that = (OCompositeKey) o;
return keys.equals(that.keys);
}
/**
* {@inheritDoc }
*/
@Override
public int hashCode() {
return keys.hashCode();
}
/**
* {@inheritDoc }
*/
@Override
public String toString() {
return "OCompositeKey{" + "keys=" + keys + '}';
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OCompositeKey.java |
4 | @Test
public class OCompositeKeyTest {
@Test
public void testEqualSameKeys() {
final OCompositeKey compositeKey = new OCompositeKey();
compositeKey.addKey("a");
compositeKey.addKey("b");
final OCompositeKey anotherCompositeKey = new OCompositeKey();
anotherCompositeKey.addKey("a");
anotherCompositeKey.addKey("b");
assertTrue(compositeKey.equals(anotherCompositeKey));
assertTrue(compositeKey.hashCode() == anotherCompositeKey.hashCode());
}
@Test
public void testEqualNotSameKeys() {
final OCompositeKey compositeKey = new OCompositeKey();
compositeKey.addKey("a");
compositeKey.addKey("b");
final OCompositeKey anotherCompositeKey = new OCompositeKey();
anotherCompositeKey.addKey("a");
anotherCompositeKey.addKey("b");
anotherCompositeKey.addKey("c");
assertFalse(compositeKey.equals(anotherCompositeKey));
}
@Test
public void testEqualNull() {
final OCompositeKey compositeKey = new OCompositeKey();
assertFalse(compositeKey.equals(null));
}
@Test
public void testEqualSame() {
final OCompositeKey compositeKey = new OCompositeKey();
assertTrue(compositeKey.equals(compositeKey));
}
@Test
public void testEqualDiffClass() {
final OCompositeKey compositeKey = new OCompositeKey();
assertFalse(compositeKey.equals("1"));
}
@Test
public void testAddKeyComparable() {
final OCompositeKey compositeKey = new OCompositeKey();
compositeKey.addKey("a");
assertEquals(compositeKey.getKeys().size(), 1);
assertTrue(compositeKey.getKeys().contains("a"));
}
@Test
public void testAddKeyComposite() {
final OCompositeKey compositeKey = new OCompositeKey();
compositeKey.addKey("a");
final OCompositeKey compositeKeyToAdd = new OCompositeKey();
compositeKeyToAdd.addKey("a");
compositeKeyToAdd.addKey("b");
compositeKey.addKey(compositeKeyToAdd);
assertEquals(compositeKey.getKeys().size(), 3);
assertTrue(compositeKey.getKeys().contains("a"));
assertTrue(compositeKey.getKeys().contains("b"));
}
@Test
public void testCompareToSame() {
final OCompositeKey compositeKey = new OCompositeKey();
compositeKey.addKey("a");
compositeKey.addKey("b");
final OCompositeKey anotherCompositeKey = new OCompositeKey();
anotherCompositeKey.addKey("a");
anotherCompositeKey.addKey("b");
assertEquals(compositeKey.compareTo(anotherCompositeKey), 0);
}
@Test
public void testCompareToPartiallyOneCase() {
final OCompositeKey compositeKey = new OCompositeKey();
compositeKey.addKey("a");
compositeKey.addKey("b");
final OCompositeKey anotherCompositeKey = new OCompositeKey();
anotherCompositeKey.addKey("a");
anotherCompositeKey.addKey("b");
anotherCompositeKey.addKey("c");
assertEquals(compositeKey.compareTo(anotherCompositeKey), 0);
}
@Test
public void testCompareToPartiallySecondCase() {
final OCompositeKey compositeKey = new OCompositeKey();
compositeKey.addKey("a");
compositeKey.addKey("b");
compositeKey.addKey("c");
final OCompositeKey anotherCompositeKey = new OCompositeKey();
anotherCompositeKey.addKey("a");
anotherCompositeKey.addKey("b");
assertEquals(compositeKey.compareTo(anotherCompositeKey), 0);
}
@Test
public void testCompareToGT() {
final OCompositeKey compositeKey = new OCompositeKey();
compositeKey.addKey("b");
final OCompositeKey anotherCompositeKey = new OCompositeKey();
anotherCompositeKey.addKey("a");
anotherCompositeKey.addKey("b");
assertEquals(compositeKey.compareTo(anotherCompositeKey), 1);
}
@Test
public void testCompareToLT() {
final OCompositeKey compositeKey = new OCompositeKey();
compositeKey.addKey("a");
compositeKey.addKey("b");
final OCompositeKey anotherCompositeKey = new OCompositeKey();
anotherCompositeKey.addKey("b");
assertEquals(compositeKey.compareTo(anotherCompositeKey), -1);
}
@Test
public void testCompareToSymmetryOne() {
final OCompositeKey compositeKeyOne = new OCompositeKey();
compositeKeyOne.addKey(1);
compositeKeyOne.addKey(2);
final OCompositeKey compositeKeyTwo = new OCompositeKey();
compositeKeyTwo.addKey(1);
compositeKeyTwo.addKey(3);
compositeKeyTwo.addKey(1);
assertEquals(compositeKeyOne.compareTo(compositeKeyTwo), -1);
assertEquals(compositeKeyTwo.compareTo(compositeKeyOne), 1);
}
@Test
public void testCompareToSymmetryTwo() {
final OCompositeKey compositeKeyOne = new OCompositeKey();
compositeKeyOne.addKey(1);
compositeKeyOne.addKey(2);
final OCompositeKey compositeKeyTwo = new OCompositeKey();
compositeKeyTwo.addKey(1);
compositeKeyTwo.addKey(2);
compositeKeyTwo.addKey(3);
assertEquals(compositeKeyOne.compareTo(compositeKeyTwo), 0);
assertEquals(compositeKeyTwo.compareTo(compositeKeyOne), 0);
}
} | false | commons_src_test_java_com_orientechnologies_common_collection_OCompositeKeyTest.java |
5 | public class OIterableObject<T> implements Iterable<T>, OResettable, Iterator<T> {
private final T object;
private boolean alreadyRead = false;
public OIterableObject(T o) {
object = o;
}
/**
* Returns an iterator over a set of elements of type T.
*
* @return an Iterator.
*/
public Iterator<T> iterator() {
return this;
}
@Override
public void reset() {
alreadyRead = false;
}
@Override
public boolean hasNext() {
return !alreadyRead;
}
@Override
public T next() {
if (!alreadyRead) {
alreadyRead = true;
return object;
} else
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove");
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OIterableObject.java |
6 | public class OIterableObjectArray<T> implements Iterable<T> {
private final Object object;
private int length;
public OIterableObjectArray(Object o) {
object = o;
length = Array.getLength(o);
}
/**
* Returns an iterator over a set of elements of type T.
*
* @return an Iterator.
*/
public Iterator<T> iterator() {
return new ObjIterator();
}
private class ObjIterator implements Iterator<T> {
private int p = 0;
/**
* Returns <tt>true</tt> if the iteration has more elements. (In other words, returns <tt>true</tt> if <tt>next</tt> would
* return an element rather than throwing an exception.)
*
* @return <tt>true</tt> if the iterator has more elements.
*/
public boolean hasNext() {
return p < length;
}
/**
* Returns the next element in the iteration.
*
* @return the next element in the iteration.
* @throws java.util.NoSuchElementException
* iteration has no more elements.
*/
@SuppressWarnings("unchecked")
public T next() {
if (p < length) {
return (T) Array.get(object, p++);
} else {
throw new NoSuchElementException();
}
}
/**
* Removes from the underlying collection the last element returned by the iterator (optional operation). This method can be
* called only once per call to <tt>next</tt>. The behavior of an iterator is unspecified if the underlying collection is
* modified while the iteration is in progress in any way other than by calling this method.
*
* @throws UnsupportedOperationException
* if the <tt>remove</tt> operation is not supported by this Iterator.
* @throws IllegalStateException
* if the <tt>next</tt> method has not yet been called, or the <tt>remove</tt> method has already been called after
* the last call to the <tt>next</tt> method.
*/
public void remove() {
throw new UnsupportedOperationException();
}
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OIterableObjectArray.java |
7 | private class ObjIterator implements Iterator<T> {
private int p = 0;
/**
* Returns <tt>true</tt> if the iteration has more elements. (In other words, returns <tt>true</tt> if <tt>next</tt> would
* return an element rather than throwing an exception.)
*
* @return <tt>true</tt> if the iterator has more elements.
*/
public boolean hasNext() {
return p < length;
}
/**
* Returns the next element in the iteration.
*
* @return the next element in the iteration.
* @throws java.util.NoSuchElementException
* iteration has no more elements.
*/
@SuppressWarnings("unchecked")
public T next() {
if (p < length) {
return (T) Array.get(object, p++);
} else {
throw new NoSuchElementException();
}
}
/**
* Removes from the underlying collection the last element returned by the iterator (optional operation). This method can be
* called only once per call to <tt>next</tt>. The behavior of an iterator is unspecified if the underlying collection is
* modified while the iteration is in progress in any way other than by calling this method.
*
* @throws UnsupportedOperationException
* if the <tt>remove</tt> operation is not supported by this Iterator.
* @throws IllegalStateException
* if the <tt>next</tt> method has not yet been called, or the <tt>remove</tt> method has already been called after
* the last call to the <tt>next</tt> method.
*/
public void remove() {
throw new UnsupportedOperationException();
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OIterableObjectArray.java |
8 | public interface OLazyIterator<T> extends Iterator<T> {
public T update(T iValue);
} | false | commons_src_main_java_com_orientechnologies_common_collection_OLazyIterator.java |
9 | public class OLazyIteratorListWrapper<T> implements OLazyIterator<T> {
private ListIterator<T> underlying;
public OLazyIteratorListWrapper(ListIterator<T> iUnderlying) {
underlying = iUnderlying;
}
public boolean hasNext() {
return underlying.hasNext();
}
public T next() {
return underlying.next();
}
public void remove() {
underlying.remove();
}
public T update(T e) {
underlying.set(e);
return null;
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OLazyIteratorListWrapper.java |
10 | @SuppressWarnings("serial")
public class OLimitedMap<K, V> extends LinkedHashMap<K, V> {
protected final int limit;
public OLimitedMap(final int initialCapacity, final float loadFactor, final int limit) {
super(initialCapacity, loadFactor, true);
this.limit = limit;
}
@Override
protected boolean removeEldestEntry(final Map.Entry<K, V> eldest) {
return limit > 0 ? size() - limit > 0 : false;
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OLimitedMap.java |
11 | @SuppressWarnings({ "unchecked", "serial" })
public abstract class OMVRBTree<K, V> extends AbstractMap<K, V> implements ONavigableMap<K, V>, Cloneable, java.io.Serializable {
private static final OAlwaysLessKey ALWAYS_LESS_KEY = new OAlwaysLessKey();
private static final OAlwaysGreaterKey ALWAYS_GREATER_KEY = new OAlwaysGreaterKey();
protected boolean pageItemFound = false;
protected int pageItemComparator = 0;
protected int pageIndex = -1;
protected float pageLoadFactor = 0.7f;
/**
* The comparator used to maintain order in this tree map, or null if it uses the natural ordering of its keys.
*
* @serial
*/
protected final Comparator<? super K> comparator;
protected transient OMVRBTreeEntry<K, V> root = null;
/**
* The number of structural modifications to the tree.
*/
transient int modCount = 0;
protected transient boolean runtimeCheckEnabled = false;
protected transient boolean debug = false;
protected Object lastSearchKey;
protected OMVRBTreeEntry<K, V> lastSearchNode;
protected boolean lastSearchFound = false;
protected int lastSearchIndex = -1;
protected int keySize = 1;
/**
* Indicates search behavior in case of {@link OCompositeKey} keys that have less amount of internal keys are used, whether lowest
* or highest partially matched key should be used. Such keys is allowed to use only in
*
* @link OMVRBTree#subMap(K, boolean, K, boolean)}, {@link OMVRBTree#tailMap(Object, boolean)} and
* {@link OMVRBTree#headMap(Object, boolean)} .
*/
public static enum PartialSearchMode {
/**
* Any partially matched key will be used as search result.
*/
NONE,
/**
* The biggest partially matched key will be used as search result.
*/
HIGHEST_BOUNDARY,
/**
* The smallest partially matched key will be used as search result.
*/
LOWEST_BOUNDARY
}
/**
* Constructs a new, empty tree map, using the natural ordering of its keys. All keys inserted into the map must implement the
* {@link Comparable} interface. Furthermore, all such keys must be <i>mutually comparable</i>: <tt>k1.compareTo(k2)</tt> must not
* throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and <tt>k2</tt> in the map. If the user attempts to put a key into
* the map that violates this constraint (for example, the user attempts to put a string key into a map whose keys are integers),
* the <tt>put(Object key, Object value)</tt> call will throw a <tt>ClassCastException</tt>.
*/
public OMVRBTree() {
this(1);
}
public OMVRBTree(int keySize) {
comparator = ODefaultComparator.INSTANCE;
init();
this.keySize = keySize;
}
/**
* Constructs a new, empty tree map, ordered according to the given comparator. All keys inserted into the map must be <i>mutually
* comparable</i> by the given comparator: <tt>comparator.compare(k1,
* k2)</tt> must not throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and <tt>k2</tt> in the map. If the user attempts
* to put a key into the map that violates this constraint, the <tt>put(Object
* key, Object value)</tt> call will throw a <tt>ClassCastException</tt>.
*
* @param iComparator
* the comparator that will be used to order this map. If <tt>null</tt>, the {@linkplain Comparable natural ordering} of
* the keys will be used.
*/
public OMVRBTree(final Comparator<? super K> iComparator) {
init();
this.comparator = iComparator;
}
/**
* Constructs a new tree map containing the same mappings as the given map, ordered according to the <i>natural ordering</i> of
* its keys. All keys inserted into the new map must implement the {@link Comparable} interface. Furthermore, all such keys must
* be <i>mutually comparable</i>: <tt>k1.compareTo(k2)</tt> must not throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt>
* and <tt>k2</tt> in the map. This method runs in n*log(n) time.
*
* @param m
* the map whose mappings are to be placed in this map
* @throws ClassCastException
* if the keys in m are not {@link Comparable}, or are not mutually comparable
* @throws NullPointerException
* if the specified map is null
*/
public OMVRBTree(final Map<? extends K, ? extends V> m) {
comparator = ODefaultComparator.INSTANCE;
init();
putAll(m);
}
/**
* Constructs a new tree map containing the same mappings and using the same ordering as the specified sorted map. This method
* runs in linear time.
*
* @param m
* the sorted map whose mappings are to be placed in this map, and whose comparator is to be used to sort this map
* @throws NullPointerException
* if the specified map is null
*/
public OMVRBTree(final SortedMap<K, ? extends V> m) {
init();
comparator = m.comparator();
try {
buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
} catch (java.io.IOException cannotHappen) {
} catch (ClassNotFoundException cannotHappen) {
}
}
/**
* Create a new entry with the first key/value to handle.
*/
protected abstract OMVRBTreeEntry<K, V> createEntry(final K key, final V value);
/**
* Create a new node with the same parent of the node is splitting.
*/
protected abstract OMVRBTreeEntry<K, V> createEntry(final OMVRBTreeEntry<K, V> parent);
protected abstract int getTreeSize();
public int getNodes() {
int counter = -1;
OMVRBTreeEntry<K, V> entry = getFirstEntry();
while (entry != null) {
entry = successor(entry);
counter++;
}
return counter;
}
protected abstract void setSize(int iSize);
public abstract int getDefaultPageSize();
/**
* Returns <tt>true</tt> if this map contains a mapping for the specified key.
*
* @param key
* key whose presence in this map is to be tested
* @return <tt>true</tt> if this map contains a mapping for the specified key
* @throws ClassCastException
* if the specified key cannot be compared with the keys currently in the map
* @throws NullPointerException
* if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
*/
@Override
public boolean containsKey(final Object key) {
return getEntry(key, PartialSearchMode.NONE) != null;
}
/**
* Returns <tt>true</tt> if this map maps one or more keys to the specified value. More formally, returns <tt>true</tt> if and
* only if this map contains at least one mapping to a value <tt>v</tt> such that
* <tt>(value==null ? v==null : value.equals(v))</tt>. This operation will probably require time linear in the map size for most
* implementations.
*
* @param value
* value whose presence in this map is to be tested
* @return <tt>true</tt> if a mapping to <tt>value</tt> exists; <tt>false</tt> otherwise
* @since 1.2
*/
@Override
public boolean containsValue(final Object value) {
for (OMVRBTreeEntry<K, V> e = getFirstEntry(); e != null; e = next(e))
if (valEquals(value, e.getValue()))
return true;
return false;
}
@Override
public int size() {
return getTreeSize();
}
/**
* Returns the value to which the specified key is mapped, or {@code null} if this map contains no mapping for the key.
*
* <p>
* More formally, if this map contains a mapping from a key {@code k} to a value {@code v} such that {@code key} compares equal to
* {@code k} according to the map's ordering, then this method returns {@code v}; otherwise it returns {@code null}. (There can be
* at most one such mapping.)
*
* <p>
* A return value of {@code null} does not <i>necessarily</i> indicate that the map contains no mapping for the key; it's also
* possible that the map explicitly maps the key to {@code null}. The {@link #containsKey containsKey} operation may be used to
* distinguish these two cases.
*
* @throws ClassCastException
* if the specified key cannot be compared with the keys currently in the map
* @throws NullPointerException
* if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
*/
@Override
public V get(final Object key) {
if (getTreeSize() == 0)
return null;
OMVRBTreeEntry<K, V> entry = null;
// TRY TO GET LATEST SEARCH
final OMVRBTreeEntry<K, V> node = getLastSearchNodeForSameKey(key);
if (node != null) {
// SAME SEARCH OF PREVIOUS ONE: REUSE LAST RESULT?
if (lastSearchFound)
// REUSE LAST RESULT, OTHERWISE THE KEY NOT EXISTS
return node.getValue(lastSearchIndex);
} else
// SEARCH THE ITEM
entry = getEntry(key, PartialSearchMode.NONE);
return entry == null ? null : entry.getValue();
}
public Comparator<? super K> comparator() {
return comparator;
}
/**
* @throws NoSuchElementException
* {@inheritDoc}
*/
public K firstKey() {
return key(getFirstEntry());
}
/**
* @throws NoSuchElementException
* {@inheritDoc}
*/
public K lastKey() {
return key(getLastEntry());
}
/**
* Copies all of the mappings from the specified map to this map. These mappings replace any mappings that this map had for any of
* the keys currently in the specified map.
*
* @param map
* mappings to be stored in this map
* @throws ClassCastException
* if the class of a key or value in the specified map prevents it from being stored in this map
* @throws NullPointerException
* if the specified map is null or the specified map contains a null key and this map does not permit null keys
*/
@Override
public void putAll(final Map<? extends K, ? extends V> map) {
int mapSize = map.size();
if (getTreeSize() == 0 && mapSize != 0 && map instanceof SortedMap) {
Comparator<?> c = ((SortedMap<? extends K, ? extends V>) map).comparator();
if (c == comparator || (c != null && c.equals(comparator))) {
++modCount;
try {
buildFromSorted(mapSize, map.entrySet().iterator(), null, null);
} catch (java.io.IOException cannotHappen) {
} catch (ClassNotFoundException cannotHappen) {
}
return;
}
}
super.putAll(map);
}
/**
* Returns this map's entry for the given key, or <tt>null</tt> if the map does not contain an entry for the key.
*
* In case of {@link OCompositeKey} keys you can specify which key can be used: lowest, highest, any.
*
* @param key
* Key to search.
* @param partialSearchMode
* Which key can be used in case of {@link OCompositeKey} key is passed in.
*
* @return this map's entry for the given key, or <tt>null</tt> if the map does not contain an entry for the key
* @throws ClassCastException
* if the specified key cannot be compared with the keys currently in the map
* @throws NullPointerException
* if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
*/
public final OMVRBTreeEntry<K, V> getEntry(final Object key, final PartialSearchMode partialSearchMode) {
return getEntry(key, false, partialSearchMode);
}
final OMVRBTreeEntry<K, V> getEntry(final Object key, final boolean iGetContainer, final PartialSearchMode partialSearchMode) {
if (key == null)
return setLastSearchNode(null, null);
pageItemFound = false;
if (getTreeSize() == 0) {
pageIndex = 0;
return iGetContainer ? root : null;
}
final K k;
if (keySize == 1)
k = (K) key;
else if (((OCompositeKey) key).getKeys().size() == keySize)
k = (K) key;
else if (partialSearchMode.equals(PartialSearchMode.NONE))
k = (K) key;
else {
final OCompositeKey fullKey = new OCompositeKey((Comparable<? super K>) key);
int itemsToAdd = keySize - fullKey.getKeys().size();
final Comparable<?> keyItem;
if (partialSearchMode.equals(PartialSearchMode.HIGHEST_BOUNDARY))
keyItem = ALWAYS_GREATER_KEY;
else
keyItem = ALWAYS_LESS_KEY;
for (int i = 0; i < itemsToAdd; i++)
fullKey.addKey(keyItem);
k = (K) fullKey;
}
OMVRBTreeEntry<K, V> p = getBestEntryPoint(k);
checkTreeStructure(p);
if (p == null)
return setLastSearchNode(key, null);
OMVRBTreeEntry<K, V> lastNode = p;
OMVRBTreeEntry<K, V> prevNode = null;
OMVRBTreeEntry<K, V> tmpNode;
int beginKey = -1;
try {
while (p != null && p.getSize() > 0) {
searchNodeCallback();
lastNode = p;
beginKey = compare(k, p.getFirstKey());
if (beginKey == 0) {
// EXACT MATCH, YOU'RE VERY LUCKY: RETURN THE FIRST KEY WITHOUT SEARCH INSIDE THE NODE
pageIndex = 0;
pageItemFound = true;
pageItemComparator = 0;
return setLastSearchNode(key, p);
}
pageItemComparator = compare(k, p.getLastKey());
if (beginKey < 0) {
if (pageItemComparator < 0) {
tmpNode = predecessor(p);
if (tmpNode != null && tmpNode != prevNode) {
// MINOR THAN THE CURRENT: GET THE LEFT NODE
prevNode = p;
p = tmpNode;
continue;
}
}
} else if (beginKey > 0) {
if (pageItemComparator > 0) {
tmpNode = successor(p);
if (tmpNode != null && tmpNode != prevNode) {
// MAJOR THAN THE CURRENT: GET THE RIGHT NODE
prevNode = p;
p = tmpNode;
continue;
}
}
}
// SEARCH INSIDE THE NODE
final V value = lastNode.search(k);
// PROBABLY PARTIAL KEY IS FOUND USE SEARCH MODE TO FIND PREFERRED ONE
if (key instanceof OCompositeKey) {
final OCompositeKey compositeKey = (OCompositeKey) key;
if (value != null && compositeKey.getKeys().size() == keySize) {
return setLastSearchNode(key, lastNode);
}
if (partialSearchMode.equals(PartialSearchMode.NONE)) {
if (value != null || iGetContainer)
return lastNode;
else
return null;
}
if (partialSearchMode.equals(PartialSearchMode.HIGHEST_BOUNDARY)) {
// FOUNDED ENTRY EITHER GREATER THAN EXISTING ITEM OR ITEM DOES NOT EXIST
return adjustHighestPartialSearchResult(iGetContainer, lastNode, compositeKey);
}
if (partialSearchMode.equals(PartialSearchMode.LOWEST_BOUNDARY)) {
return adjustLowestPartialSearchResult(iGetContainer, lastNode, compositeKey);
}
}
if (value != null) {
setLastSearchNode(key, lastNode);
}
if (value != null || iGetContainer)
// FOUND: RETURN CURRENT NODE OR AT LEAST THE CONTAINER NODE
return lastNode;
// NOT FOUND
return null;
}
} finally {
checkTreeStructure(p);
}
return setLastSearchNode(key, null);
}
private OMVRBTreeEntry<K, V> adjustHighestPartialSearchResult(final boolean iGetContainer, final OMVRBTreeEntry<K, V> lastNode,
final OCompositeKey compositeKey) {
final int oldPageIndex = pageIndex;
final OMVRBTreeEntry<K, V> prevNd = previous(lastNode);
if (prevNd == null) {
pageIndex = oldPageIndex;
pageItemFound = false;
if (iGetContainer)
return lastNode;
return null;
}
pageItemComparator = compare(prevNd.getKey(), compositeKey);
if (pageItemComparator == 0) {
pageItemFound = true;
return prevNd;
} else if (pageItemComparator > 1) {
pageItemFound = false;
if (iGetContainer)
return prevNd;
return null;
} else {
pageIndex = oldPageIndex;
pageItemFound = false;
if (iGetContainer)
return lastNode;
return null;
}
}
private OMVRBTreeEntry<K, V> adjustLowestPartialSearchResult(final boolean iGetContainer, OMVRBTreeEntry<K, V> lastNode,
final OCompositeKey compositeKey) {
// RARE CASE WHEN NODE ITSELF DOES CONTAIN KEY, BUT ALL KEYS LESS THAN GIVEN ONE
final int oldPageIndex = pageIndex;
final OMVRBTreeEntry<K, V> oldNode = lastNode;
if (pageIndex >= lastNode.getSize()) {
lastNode = next(lastNode);
if (lastNode == null) {
lastNode = oldNode;
pageIndex = oldPageIndex;
pageItemFound = false;
if (iGetContainer)
return lastNode;
return null;
}
}
pageItemComparator = compare(lastNode.getKey(), compositeKey);
if (pageItemComparator == 0) {
pageItemFound = true;
return lastNode;
} else {
pageItemFound = false;
if (iGetContainer)
return lastNode;
return null;
}
}
/**
* Basic implementation that returns the root node.
*/
protected OMVRBTreeEntry<K, V> getBestEntryPoint(final K key) {
return root;
}
/**
* Gets the entry corresponding to the specified key; if no such entry exists, returns the entry for the least key greater than
* the specified key; if no such entry exists (i.e., the greatest key in the Tree is less than the specified key), returns
* <tt>null</tt>.
*
* @param key
* Key to search.
* @param partialSearchMode
* In case of {@link OCompositeKey} key is passed in this parameter will be used to find preferred one.
*/
public OMVRBTreeEntry<K, V> getCeilingEntry(final K key, final PartialSearchMode partialSearchMode) {
OMVRBTreeEntry<K, V> p = getEntry(key, true, partialSearchMode);
if (p == null)
return null;
if (pageItemFound)
return p;
// NOT MATCHED, POSITION IS ALREADY TO THE NEXT ONE
else if (pageIndex < p.getSize()) {
if (key instanceof OCompositeKey)
return adjustSearchResult((OCompositeKey) key, partialSearchMode, p);
else
return p;
}
return null;
}
/**
* Gets the entry corresponding to the specified key; if no such entry exists, returns the entry for the greatest key less than
* the specified key; if no such entry exists, returns <tt>null</tt>.
*
* @param key
* Key to search.
* @param partialSearchMode
* In case of {@link OCompositeKey} composite key is passed in this parameter will be used to find preferred one.
*/
public OMVRBTreeEntry<K, V> getFloorEntry(final K key, final PartialSearchMode partialSearchMode) {
OMVRBTreeEntry<K, V> p = getEntry(key, true, partialSearchMode);
if (p == null)
return null;
if (pageItemFound)
return p;
final OMVRBTreeEntry<K, V> adjacentEntry = previous(p);
if (adjacentEntry == null)
return null;
if (key instanceof OCompositeKey) {
return adjustSearchResult((OCompositeKey) key, partialSearchMode, adjacentEntry);
}
return adjacentEntry;
}
private OMVRBTreeEntry<K, V> adjustSearchResult(final OCompositeKey key, final PartialSearchMode partialSearchMode,
final OMVRBTreeEntry<K, V> foundEntry) {
if (partialSearchMode.equals(PartialSearchMode.NONE))
return foundEntry;
final OCompositeKey keyToSearch = key;
final OCompositeKey foundKey = (OCompositeKey) foundEntry.getKey();
if (keyToSearch.getKeys().size() < keySize) {
final OCompositeKey borderKey = new OCompositeKey();
final OCompositeKey keyToCompare = new OCompositeKey();
final List<Object> keyItems = foundKey.getKeys();
for (int i = 0; i < keySize - 1; i++) {
final Object keyItem = keyItems.get(i);
borderKey.addKey(keyItem);
if (i < keyToSearch.getKeys().size())
keyToCompare.addKey(keyItem);
}
if (partialSearchMode.equals(PartialSearchMode.HIGHEST_BOUNDARY))
borderKey.addKey(ALWAYS_GREATER_KEY);
else
borderKey.addKey(ALWAYS_LESS_KEY);
final OMVRBTreeEntry<K, V> adjustedNode = getEntry(borderKey, true, PartialSearchMode.NONE);
if (partialSearchMode.equals(PartialSearchMode.HIGHEST_BOUNDARY))
return adjustHighestPartialSearchResult(false, adjustedNode, keyToCompare);
else
return adjustLowestPartialSearchResult(false, adjustedNode, keyToCompare);
}
return foundEntry;
}
/**
* Gets the entry for the least key greater than the specified key; if no such entry exists, returns the entry for the least key
* greater than the specified key; if no such entry exists returns <tt>null</tt>.
*/
public OMVRBTreeEntry<K, V> getHigherEntry(final K key) {
final OMVRBTreeEntry<K, V> p = getEntry(key, true, PartialSearchMode.HIGHEST_BOUNDARY);
if (p == null)
return null;
if (pageItemFound)
// MATCH, RETURN THE NEXT ONE
return next(p);
else if (pageIndex < p.getSize())
// NOT MATCHED, POSITION IS ALREADY TO THE NEXT ONE
return p;
return null;
}
/**
* Returns the entry for the greatest key less than the specified key; if no such entry exists (i.e., the least key in the Tree is
* greater than the specified key), returns <tt>null</tt>.
*/
public OMVRBTreeEntry<K, V> getLowerEntry(final K key) {
final OMVRBTreeEntry<K, V> p = getEntry(key, true, PartialSearchMode.LOWEST_BOUNDARY);
if (p == null)
return null;
return previous(p);
}
/**
* Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the
* old value is replaced.
*
* @param key
* key with which the specified value is to be associated
* @param value
* value to be associated with the specified key
*
* @return the previous value associated with <tt>key</tt>, or <tt>null</tt> if there was no mapping for <tt>key</tt>. (A
* <tt>null</tt> return can also indicate that the map previously associated <tt>null</tt> with <tt>key</tt>.)
* @throws ClassCastException
* if the specified key cannot be compared with the keys currently in the map
* @throws NullPointerException
* if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
*/
@Override
public V put(final K key, final V value) {
OMVRBTreeEntry<K, V> parentNode = null;
try {
if (root == null) {
root = createEntry(key, value);
root.setColor(BLACK);
setSize(1);
modCount++;
return null;
}
// TRY TO GET LATEST SEARCH
parentNode = getLastSearchNodeForSameKey(key);
if (parentNode != null) {
if (lastSearchFound) {
// EXACT MATCH: UPDATE THE VALUE
pageIndex = lastSearchIndex;
modCount++;
return parentNode.setValue(value);
}
}
// SEARCH THE ITEM
parentNode = getEntry(key, true, PartialSearchMode.NONE);
if (pageItemFound) {
modCount++;
// EXACT MATCH: UPDATE THE VALUE
return parentNode.setValue(value);
}
setLastSearchNode(null, null);
if (parentNode == null) {
parentNode = root;
pageIndex = 0;
}
if (parentNode.getFreeSpace() > 0) {
// INSERT INTO THE PAGE
parentNode.insert(pageIndex, key, value);
} else {
// CREATE NEW NODE AND COPY HALF OF VALUES FROM THE ORIGIN TO THE NEW ONE IN ORDER TO GET VALUES BALANCED
final OMVRBTreeEntry<K, V> newNode = createEntry(parentNode);
if (pageIndex < parentNode.getPageSplitItems())
// INSERT IN THE ORIGINAL NODE
parentNode.insert(pageIndex, key, value);
else
// INSERT IN THE NEW NODE
newNode.insert(pageIndex - parentNode.getPageSplitItems(), key, value);
OMVRBTreeEntry<K, V> node = parentNode.getRight();
OMVRBTreeEntry<K, V> prevNode = parentNode;
int cmp = 0;
final K fk = newNode.getFirstKey();
if (comparator != null)
while (node != null) {
cmp = comparator.compare(fk, node.getFirstKey());
if (cmp < 0) {
prevNode = node;
node = node.getLeft();
} else if (cmp > 0) {
prevNode = node;
node = node.getRight();
} else {
throw new IllegalStateException("Duplicated keys were found in OMVRBTree.");
}
}
else
while (node != null) {
cmp = compare(fk, node.getFirstKey());
if (cmp < 0) {
prevNode = node;
node = node.getLeft();
} else if (cmp > 0) {
prevNode = node;
node = node.getRight();
} else {
throw new IllegalStateException("Duplicated keys were found in OMVRBTree.");
}
}
if (prevNode == parentNode)
parentNode.setRight(newNode);
else if (cmp < 0)
prevNode.setLeft(newNode);
else if (cmp > 0)
prevNode.setRight(newNode);
else
throw new IllegalStateException("Duplicated keys were found in OMVRBTree.");
fixAfterInsertion(newNode);
}
modCount++;
setSizeDelta(+1);
} finally {
checkTreeStructure(parentNode);
}
return null;
}
/**
* Removes the mapping for this key from this OMVRBTree if present.
*
* @param key
* key for which mapping should be removed
* @return the previous value associated with <tt>key</tt>, or <tt>null</tt> if there was no mapping for <tt>key</tt>. (A
* <tt>null</tt> return can also indicate that the map previously associated <tt>null</tt> with <tt>key</tt>.)
* @throws ClassCastException
* if the specified key cannot be compared with the keys currently in the map
* @throws NullPointerException
* if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
*/
@Override
public V remove(final Object key) {
OMVRBTreeEntry<K, V> p = getEntry(key, PartialSearchMode.NONE);
setLastSearchNode(null, null);
if (p == null)
return null;
V oldValue = p.getValue();
deleteEntry(p);
return oldValue;
}
/**
* Removes all of the mappings from this map. The map will be empty after this call returns.
*/
@Override
public void clear() {
modCount++;
setSize(0);
setLastSearchNode(null, null);
setRoot(null);
}
/**
* Returns a shallow copy of this <tt>OMVRBTree</tt> instance. (The keys and values themselves are not cloned.)
*
* @return a shallow copy of this map
*/
@Override
public Object clone() {
OMVRBTree<K, V> clone = null;
try {
clone = (OMVRBTree<K, V>) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
// Put clone into "virgin" state (except for comparator)
clone.pageIndex = pageIndex;
clone.pageItemFound = pageItemFound;
clone.pageLoadFactor = pageLoadFactor;
clone.root = null;
clone.setSize(0);
clone.modCount = 0;
clone.entrySet = null;
clone.navigableKeySet = null;
clone.descendingMap = null;
// Initialize clone with our mappings
try {
clone.buildFromSorted(getTreeSize(), entrySet().iterator(), null, null);
} catch (java.io.IOException cannotHappen) {
} catch (ClassNotFoundException cannotHappen) {
}
return clone;
}
// ONavigableMap API methods
/**
* @since 1.6
*/
public Map.Entry<K, V> firstEntry() {
return exportEntry(getFirstEntry());
}
/**
* @since 1.6
*/
public Map.Entry<K, V> lastEntry() {
return exportEntry(getLastEntry());
}
/**
* @since 1.6
*/
public Entry<K, V> pollFirstEntry() {
OMVRBTreeEntry<K, V> p = getFirstEntry();
Map.Entry<K, V> result = exportEntry(p);
if (p != null)
deleteEntry(p);
return result;
}
/**
* @since 1.6
*/
public Entry<K, V> pollLastEntry() {
OMVRBTreeEntry<K, V> p = getLastEntry();
Map.Entry<K, V> result = exportEntry(p);
if (p != null)
deleteEntry(p);
return result;
}
/**
* @throws ClassCastException
* {@inheritDoc}
* @throws NullPointerException
* if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
* @since 1.6
*/
public Map.Entry<K, V> lowerEntry(final K key) {
return exportEntry(getLowerEntry(key));
}
/**
* @throws ClassCastException
* {@inheritDoc}
* @throws NullPointerException
* if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
* @since 1.6
*/
public K lowerKey(final K key) {
return keyOrNull(getLowerEntry(key));
}
/**
* @throws ClassCastException
* {@inheritDoc}
* @throws NullPointerException
* if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
* @since 1.6
*/
public Map.Entry<K, V> floorEntry(final K key) {
return exportEntry(getFloorEntry(key, PartialSearchMode.NONE));
}
/**
* @throws ClassCastException
* {@inheritDoc}
* @throws NullPointerException
* if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
* @since 1.6
*/
public K floorKey(final K key) {
return keyOrNull(getFloorEntry(key, PartialSearchMode.NONE));
}
/**
* @throws ClassCastException
* {@inheritDoc}
* @throws NullPointerException
* if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
* @since 1.6
*/
public Map.Entry<K, V> ceilingEntry(final K key) {
return exportEntry(getCeilingEntry(key, PartialSearchMode.NONE));
}
/**
* @throws ClassCastException
* {@inheritDoc}
* @throws NullPointerException
* if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
* @since 1.6
*/
public K ceilingKey(final K key) {
return keyOrNull(getCeilingEntry(key, PartialSearchMode.NONE));
}
/**
* @throws ClassCastException
* {@inheritDoc}
* @throws NullPointerException
* if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
* @since 1.6
*/
public Map.Entry<K, V> higherEntry(final K key) {
return exportEntry(getHigherEntry(key));
}
/**
* @throws ClassCastException
* {@inheritDoc}
* @throws NullPointerException
* if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
* @since 1.6
*/
public K higherKey(final K key) {
return keyOrNull(getHigherEntry(key));
}
// Views
/**
* Fields initialized to contain an instance of the entry set view the first time this view is requested. Views are stateless, so
* there's no reason to create more than one.
*/
private transient EntrySet entrySet = null;
private transient KeySet<K> navigableKeySet = null;
private transient ONavigableMap<K, V> descendingMap = null;
/**
* Returns a {@link Set} view of the keys contained in this map. The set's iterator returns the keys in ascending order. The set
* is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration
* over the set is in progress (except through the iterator's own <tt>remove</tt> operation), the results of the iteration are
* undefined. The set supports element removal, which removes the corresponding mapping from the map, via the
* <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations. It does
* not support the <tt>add</tt> or <tt>addAll</tt> operations.
*/
@Override
public Set<K> keySet() {
return navigableKeySet();
}
/**
* @since 1.6
*/
public ONavigableSet<K> navigableKeySet() {
final KeySet<K> nks = navigableKeySet;
return (nks != null) ? nks : (navigableKeySet = (KeySet<K>) new KeySet<Object>((ONavigableMap<Object, Object>) this));
}
/**
* @since 1.6
*/
public ONavigableSet<K> descendingKeySet() {
return descendingMap().navigableKeySet();
}
/**
* Returns a {@link Collection} view of the values contained in this map. The collection's iterator returns the values in
* ascending order of the corresponding keys. The collection is backed by the map, so changes to the map are reflected in the
* collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the
* iterator's own <tt>remove</tt> operation), the results of the iteration are undefined. The collection supports element removal,
* which removes the corresponding mapping from the map, via the <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
* <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt> operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
* operations.
*/
@Override
public Collection<V> values() {
final Collection<V> vs = new Values();
return (vs != null) ? vs : null;
}
/**
* Returns a {@link Set} view of the mappings contained in this map. The set's iterator returns the entries in ascending key
* order. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through the iterator's own <tt>remove</tt> operation, or through the
* <tt>setValue</tt> operation on a map entry returned by the iterator) the results of the iteration are undefined. The set
* supports element removal, which removes the corresponding mapping from the map, via the <tt>Iterator.remove</tt>,
* <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt> operations. It does not support the <tt>add</tt>
* or <tt>addAll</tt> operations.
*/
@Override
public Set<Map.Entry<K, V>> entrySet() {
final EntrySet es = entrySet;
return (es != null) ? es : (entrySet = new EntrySet());
}
/**
* @since 1.6
*/
public ONavigableMap<K, V> descendingMap() {
final ONavigableMap<K, V> km = descendingMap;
return (km != null) ? km : (descendingMap = new DescendingSubMap<K, V>(this, true, null, true, true, null, true));
}
/**
* @throws ClassCastException
* {@inheritDoc}
* @throws NullPointerException
* if <tt>fromKey</tt> or <tt>toKey</tt> is null and this map uses natural ordering, or its comparator does not permit
* null keys
* @throws IllegalArgumentException
* {@inheritDoc}
* @since 1.6
*/
public ONavigableMap<K, V> subMap(final K fromKey, final boolean fromInclusive, final K toKey, final boolean toInclusive) {
return new AscendingSubMap<K, V>(this, false, fromKey, fromInclusive, false, toKey, toInclusive);
}
/**
* @throws ClassCastException
* {@inheritDoc}
* @throws NullPointerException
* if <tt>toKey</tt> is null and this map uses natural ordering, or its comparator does not permit null keys
* @throws IllegalArgumentException
* {@inheritDoc}
* @since 1.6
*/
public ONavigableMap<K, V> headMap(final K toKey, final boolean inclusive) {
return new AscendingSubMap<K, V>(this, true, null, true, false, toKey, inclusive);
}
/**
* @throws ClassCastException
* {@inheritDoc}
* @throws NullPointerException
* if <tt>fromKey</tt> is null and this map uses natural ordering, or its comparator does not permit null keys
* @throws IllegalArgumentException
* {@inheritDoc}
* @since 1.6
*/
public ONavigableMap<K, V> tailMap(final K fromKey, final boolean inclusive) {
return new AscendingSubMap<K, V>(this, false, fromKey, inclusive, true, null, true);
}
/**
* @throws ClassCastException
* {@inheritDoc}
* @throws NullPointerException
* if <tt>fromKey</tt> or <tt>toKey</tt> is null and this map uses natural ordering, or its comparator does not permit
* null keys
* @throws IllegalArgumentException
* {@inheritDoc}
*/
public SortedMap<K, V> subMap(final K fromKey, final K toKey) {
return subMap(fromKey, true, toKey, false);
}
/**
* @throws ClassCastException
* {@inheritDoc}
* @throws NullPointerException
* if <tt>toKey</tt> is null and this map uses natural ordering, or its comparator does not permit null keys
* @throws IllegalArgumentException
* {@inheritDoc}
*/
public SortedMap<K, V> headMap(final K toKey) {
return headMap(toKey, false);
}
/**
* @throws ClassCastException
* {@inheritDoc}
* @throws NullPointerException
* if <tt>fromKey</tt> is null and this map uses natural ordering, or its comparator does not permit null keys
* @throws IllegalArgumentException
* {@inheritDoc}
*/
public SortedMap<K, V> tailMap(final K fromKey) {
return tailMap(fromKey, true);
}
// View class support
public class Values extends AbstractCollection<V> {
@Override
public Iterator<V> iterator() {
return new ValueIterator(getFirstEntry());
}
public Iterator<V> inverseIterator() {
return new ValueInverseIterator(getLastEntry());
}
@Override
public int size() {
return OMVRBTree.this.size();
}
@Override
public boolean contains(final Object o) {
return OMVRBTree.this.containsValue(o);
}
@Override
public boolean remove(final Object o) {
for (OMVRBTreeEntry<K, V> e = getFirstEntry(); e != null; e = next(e)) {
if (valEquals(e.getValue(), o)) {
deleteEntry(e);
return true;
}
}
return false;
}
@Override
public void clear() {
OMVRBTree.this.clear();
}
}
public class EntrySet extends AbstractSet<Map.Entry<K, V>> {
@Override
public Iterator<Map.Entry<K, V>> iterator() {
return new EntryIterator(getFirstEntry());
}
public Iterator<Map.Entry<K, V>> inverseIterator() {
return new InverseEntryIterator(getLastEntry());
}
@Override
public boolean contains(final Object o) {
if (!(o instanceof Map.Entry))
return false;
OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o;
final V value = entry.getValue();
final V p = get(entry.getKey());
return p != null && valEquals(p, value);
}
@Override
public boolean remove(final Object o) {
if (!(o instanceof Map.Entry))
return false;
final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o;
final V value = entry.getValue();
OMVRBTreeEntry<K, V> p = getEntry(entry.getKey(), PartialSearchMode.NONE);
if (p != null && valEquals(p.getValue(), value)) {
deleteEntry(p);
return true;
}
return false;
}
@Override
public int size() {
return OMVRBTree.this.size();
}
@Override
public void clear() {
OMVRBTree.this.clear();
}
}
/*
* Unlike Values and EntrySet, the KeySet class is static, delegating to a ONavigableMap to allow use by SubMaps, which outweighs
* the ugliness of needing type-tests for the following Iterator methods that are defined appropriately in main versus submap
* classes.
*/
OLazyIterator<K> keyIterator() {
return new KeyIterator(getFirstEntry());
}
OLazyIterator<K> descendingKeyIterator() {
return new DescendingKeyIterator(getLastEntry());
}
@SuppressWarnings("rawtypes")
static final class KeySet<E> extends AbstractSet<E> implements ONavigableSet<E> {
private final ONavigableMap<E, Object> m;
KeySet(ONavigableMap<E, Object> map) {
m = map;
}
@Override
public OLazyIterator<E> iterator() {
if (m instanceof OMVRBTree)
return ((OMVRBTree<E, Object>) m).keyIterator();
else
return (((OMVRBTree.NavigableSubMap) m).keyIterator());
}
public OLazyIterator<E> descendingIterator() {
if (m instanceof OMVRBTree)
return ((OMVRBTree<E, Object>) m).descendingKeyIterator();
else
return (((OMVRBTree.NavigableSubMap) m).descendingKeyIterator());
}
@Override
public int size() {
return m.size();
}
@Override
public boolean isEmpty() {
return m.isEmpty();
}
@Override
public boolean contains(final Object o) {
return m.containsKey(o);
}
@Override
public void clear() {
m.clear();
}
public E lower(final E e) {
return m.lowerKey(e);
}
public E floor(final E e) {
return m.floorKey(e);
}
public E ceiling(final E e) {
return m.ceilingKey(e);
}
public E higher(final E e) {
return m.higherKey(e);
}
public E first() {
return m.firstKey();
}
public E last() {
return m.lastKey();
}
public Comparator<? super E> comparator() {
return m.comparator();
}
public E pollFirst() {
final Map.Entry<E, Object> e = m.pollFirstEntry();
return e == null ? null : e.getKey();
}
public E pollLast() {
final Map.Entry<E, Object> e = m.pollLastEntry();
return e == null ? null : e.getKey();
}
@Override
public boolean remove(final Object o) {
final int oldSize = size();
m.remove(o);
return size() != oldSize;
}
public ONavigableSet<E> subSet(final E fromElement, final boolean fromInclusive, final E toElement, final boolean toInclusive) {
return new OMVRBTreeSet<E>(m.subMap(fromElement, fromInclusive, toElement, toInclusive));
}
public ONavigableSet<E> headSet(final E toElement, final boolean inclusive) {
return new OMVRBTreeSet<E>(m.headMap(toElement, inclusive));
}
public ONavigableSet<E> tailSet(final E fromElement, final boolean inclusive) {
return new OMVRBTreeSet<E>(m.tailMap(fromElement, inclusive));
}
public SortedSet<E> subSet(final E fromElement, final E toElement) {
return subSet(fromElement, true, toElement, false);
}
public SortedSet<E> headSet(final E toElement) {
return headSet(toElement, false);
}
public SortedSet<E> tailSet(final E fromElement) {
return tailSet(fromElement, true);
}
public ONavigableSet<E> descendingSet() {
return new OMVRBTreeSet<E>(m.descendingMap());
}
}
final class EntryIterator extends AbstractEntryIterator<K, V, Map.Entry<K, V>> {
EntryIterator(final OMVRBTreeEntry<K, V> first) {
super(first);
}
public Map.Entry<K, V> next() {
return nextEntry();
}
}
final class InverseEntryIterator extends AbstractEntryIterator<K, V, Map.Entry<K, V>> {
InverseEntryIterator(final OMVRBTreeEntry<K, V> last) {
super(last);
// we have to set ourselves after current index to make iterator work
if (last != null) {
pageIndex = last.getTree().getPageIndex() + 1;
}
}
public Map.Entry<K, V> next() {
return prevEntry();
}
}
final class ValueIterator extends AbstractEntryIterator<K, V, V> {
ValueIterator(final OMVRBTreeEntry<K, V> first) {
super(first);
}
@Override
public V next() {
return nextValue();
}
}
final class ValueInverseIterator extends AbstractEntryIterator<K, V, V> {
ValueInverseIterator(final OMVRBTreeEntry<K, V> last) {
super(last);
// we have to set ourselves after current index to make iterator work
if (last != null) {
pageIndex = last.getTree().getPageIndex() + 1;
}
}
@Override
public boolean hasNext() {
return hasPrevious();
}
@Override
public V next() {
return prevValue();
}
}
final class KeyIterator extends AbstractEntryIterator<K, V, K> {
KeyIterator(final OMVRBTreeEntry<K, V> first) {
super(first);
}
@Override
public K next() {
return nextKey();
}
}
final class DescendingKeyIterator extends AbstractEntryIterator<K, V, K> {
DescendingKeyIterator(final OMVRBTreeEntry<K, V> first) {
super(first);
}
public K next() {
return prevEntry().getKey();
}
}
// Little utilities
/**
* Compares two keys using the correct comparison method for this OMVRBTree.
*/
final int compare(final Object k1, final Object k2) {
return comparator == null ? ((Comparable<? super K>) k1).compareTo((K) k2) : comparator.compare((K) k1, (K) k2);
}
/**
* Test two values for equality. Differs from o1.equals(o2) only in that it copes with <tt>null</tt> o1 properly.
*/
final static boolean valEquals(final Object o1, final Object o2) {
return (o1 == null ? o2 == null : o1.equals(o2));
}
/**
* Return SimpleImmutableEntry for entry, or null if null
*/
static <K, V> Map.Entry<K, V> exportEntry(final OMVRBTreeEntry<K, V> omvrbTreeEntryPosition) {
return omvrbTreeEntryPosition == null ? null : new OSimpleImmutableEntry<K, V>(omvrbTreeEntryPosition);
}
/**
* Return SimpleImmutableEntry for entry, or null if null
*/
static <K, V> Map.Entry<K, V> exportEntry(final OMVRBTreeEntryPosition<K, V> omvrbTreeEntryPosition) {
return omvrbTreeEntryPosition == null ? null : new OSimpleImmutableEntry<K, V>(omvrbTreeEntryPosition.entry);
}
/**
* Return key for entry, or null if null
*/
static <K, V> K keyOrNull(final OMVRBTreeEntry<K, V> e) {
return e == null ? null : e.getKey();
}
/**
* Return key for entry, or null if null
*/
static <K, V> K keyOrNull(OMVRBTreeEntryPosition<K, V> e) {
return e == null ? null : e.getKey();
}
/**
* Returns the key corresponding to the specified Entry.
*
* @throws NoSuchElementException
* if the Entry is null
*/
static <K> K key(OMVRBTreeEntry<K, ?> e) {
if (e == null)
throw new NoSuchElementException();
return e.getKey();
}
// SubMaps
/**
* @serial include
*/
static abstract class NavigableSubMap<K, V> extends AbstractMap<K, V> implements ONavigableMap<K, V>, java.io.Serializable {
/**
* The backing map.
*/
final OMVRBTree<K, V> m;
/**
* Endpoints are represented as triples (fromStart, lo, loInclusive) and (toEnd, hi, hiInclusive). If fromStart is true, then
* the low (absolute) bound is the start of the backing map, and the other values are ignored. Otherwise, if loInclusive is
* true, lo is the inclusive bound, else lo is the exclusive bound. Similarly for the upper bound.
*/
final K lo, hi;
final boolean fromStart, toEnd;
final boolean loInclusive, hiInclusive;
NavigableSubMap(final OMVRBTree<K, V> m, final boolean fromStart, K lo, final boolean loInclusive, final boolean toEnd, K hi,
final boolean hiInclusive) {
if (!fromStart && !toEnd) {
if (m.compare(lo, hi) > 0)
throw new IllegalArgumentException("fromKey > toKey");
} else {
if (!fromStart) // type check
m.compare(lo, lo);
if (!toEnd)
m.compare(hi, hi);
}
this.m = m;
this.fromStart = fromStart;
this.lo = lo;
this.loInclusive = loInclusive;
this.toEnd = toEnd;
this.hi = hi;
this.hiInclusive = hiInclusive;
}
// internal utilities
final boolean tooLow(final Object key) {
if (!fromStart) {
int c = m.compare(key, lo);
if (c < 0 || (c == 0 && !loInclusive))
return true;
}
return false;
}
final boolean tooHigh(final Object key) {
if (!toEnd) {
int c = m.compare(key, hi);
if (c > 0 || (c == 0 && !hiInclusive))
return true;
}
return false;
}
final boolean inRange(final Object key) {
return !tooLow(key) && !tooHigh(key);
}
final boolean inClosedRange(final Object key) {
return (fromStart || m.compare(key, lo) >= 0) && (toEnd || m.compare(hi, key) >= 0);
}
final boolean inRange(final Object key, final boolean inclusive) {
return inclusive ? inRange(key) : inClosedRange(key);
}
/*
* Absolute versions of relation operations. Subclasses map to these using like-named "sub" versions that invert senses for
* descending maps
*/
final OMVRBTreeEntryPosition<K, V> absLowest() {
OMVRBTreeEntry<K, V> e = (fromStart ? m.getFirstEntry() : (loInclusive ? m.getCeilingEntry(lo,
PartialSearchMode.LOWEST_BOUNDARY) : m.getHigherEntry(lo)));
return (e == null || tooHigh(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e);
}
final OMVRBTreeEntryPosition<K, V> absHighest() {
OMVRBTreeEntry<K, V> e = (toEnd ? m.getLastEntry() : (hiInclusive ? m.getFloorEntry(hi, PartialSearchMode.HIGHEST_BOUNDARY)
: m.getLowerEntry(hi)));
return (e == null || tooLow(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e);
}
final OMVRBTreeEntryPosition<K, V> absCeiling(K key) {
if (tooLow(key))
return absLowest();
OMVRBTreeEntry<K, V> e = m.getCeilingEntry(key, PartialSearchMode.NONE);
return (e == null || tooHigh(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e);
}
final OMVRBTreeEntryPosition<K, V> absHigher(K key) {
if (tooLow(key))
return absLowest();
OMVRBTreeEntry<K, V> e = m.getHigherEntry(key);
return (e == null || tooHigh(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e);
}
final OMVRBTreeEntryPosition<K, V> absFloor(K key) {
if (tooHigh(key))
return absHighest();
OMVRBTreeEntry<K, V> e = m.getFloorEntry(key, PartialSearchMode.NONE);
return (e == null || tooLow(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e);
}
final OMVRBTreeEntryPosition<K, V> absLower(K key) {
if (tooHigh(key))
return absHighest();
OMVRBTreeEntry<K, V> e = m.getLowerEntry(key);
return (e == null || tooLow(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e);
}
/** Returns the absolute high fence for ascending traversal */
final OMVRBTreeEntryPosition<K, V> absHighFence() {
return (toEnd ? null : new OMVRBTreeEntryPosition<K, V>(hiInclusive ? m.getHigherEntry(hi) : m.getCeilingEntry(hi,
PartialSearchMode.LOWEST_BOUNDARY)));
}
/** Return the absolute low fence for descending traversal */
final OMVRBTreeEntryPosition<K, V> absLowFence() {
return (fromStart ? null : new OMVRBTreeEntryPosition<K, V>(loInclusive ? m.getLowerEntry(lo) : m.getFloorEntry(lo,
PartialSearchMode.HIGHEST_BOUNDARY)));
}
// Abstract methods defined in ascending vs descending classes
// These relay to the appropriate absolute versions
abstract OMVRBTreeEntry<K, V> subLowest();
abstract OMVRBTreeEntry<K, V> subHighest();
abstract OMVRBTreeEntry<K, V> subCeiling(K key);
abstract OMVRBTreeEntry<K, V> subHigher(K key);
abstract OMVRBTreeEntry<K, V> subFloor(K key);
abstract OMVRBTreeEntry<K, V> subLower(K key);
/** Returns ascending iterator from the perspective of this submap */
abstract OLazyIterator<K> keyIterator();
/** Returns descending iterator from the perspective of this submap */
abstract OLazyIterator<K> descendingKeyIterator();
// public methods
@Override
public boolean isEmpty() {
return (fromStart && toEnd) ? m.isEmpty() : entrySet().isEmpty();
}
@Override
public int size() {
return (fromStart && toEnd) ? m.size() : entrySet().size();
}
@Override
public final boolean containsKey(Object key) {
return inRange(key) && m.containsKey(key);
}
@Override
public final V put(K key, V value) {
if (!inRange(key))
throw new IllegalArgumentException("key out of range");
return m.put(key, value);
}
@Override
public final V get(Object key) {
return !inRange(key) ? null : m.get(key);
}
@Override
public final V remove(Object key) {
return !inRange(key) ? null : m.remove(key);
}
public final Map.Entry<K, V> ceilingEntry(K key) {
return exportEntry(subCeiling(key));
}
public final K ceilingKey(K key) {
return keyOrNull(subCeiling(key));
}
public final Map.Entry<K, V> higherEntry(K key) {
return exportEntry(subHigher(key));
}
public final K higherKey(K key) {
return keyOrNull(subHigher(key));
}
public final Map.Entry<K, V> floorEntry(K key) {
return exportEntry(subFloor(key));
}
public final K floorKey(K key) {
return keyOrNull(subFloor(key));
}
public final Map.Entry<K, V> lowerEntry(K key) {
return exportEntry(subLower(key));
}
public final K lowerKey(K key) {
return keyOrNull(subLower(key));
}
public final K firstKey() {
return key(subLowest());
}
public final K lastKey() {
return key(subHighest());
}
public final Map.Entry<K, V> firstEntry() {
return exportEntry(subLowest());
}
public final Map.Entry<K, V> lastEntry() {
return exportEntry(subHighest());
}
public final Map.Entry<K, V> pollFirstEntry() {
OMVRBTreeEntry<K, V> e = subLowest();
Map.Entry<K, V> result = exportEntry(e);
if (e != null)
m.deleteEntry(e);
return result;
}
public final Map.Entry<K, V> pollLastEntry() {
OMVRBTreeEntry<K, V> e = subHighest();
Map.Entry<K, V> result = exportEntry(e);
if (e != null)
m.deleteEntry(e);
return result;
}
// Views
transient ONavigableMap<K, V> descendingMapView = null;
transient EntrySetView entrySetView = null;
transient KeySet<K> navigableKeySetView = null;
@SuppressWarnings("rawtypes")
public final ONavigableSet<K> navigableKeySet() {
KeySet<K> nksv = navigableKeySetView;
return (nksv != null) ? nksv : (navigableKeySetView = new OMVRBTree.KeySet(this));
}
@Override
public final Set<K> keySet() {
return navigableKeySet();
}
public ONavigableSet<K> descendingKeySet() {
return descendingMap().navigableKeySet();
}
public final SortedMap<K, V> subMap(final K fromKey, final K toKey) {
return subMap(fromKey, true, toKey, false);
}
public final SortedMap<K, V> headMap(final K toKey) {
return headMap(toKey, false);
}
public final SortedMap<K, V> tailMap(final K fromKey) {
return tailMap(fromKey, true);
}
// View classes
abstract class EntrySetView extends AbstractSet<Map.Entry<K, V>> {
private transient int size = -1, sizeModCount;
@Override
public int size() {
if (fromStart && toEnd)
return m.size();
if (size == -1 || sizeModCount != m.modCount) {
sizeModCount = m.modCount;
size = 0;
Iterator<?> i = iterator();
while (i.hasNext()) {
size++;
i.next();
}
}
return size;
}
@Override
public boolean isEmpty() {
OMVRBTreeEntryPosition<K, V> n = absLowest();
return n == null || tooHigh(n.getKey());
}
@Override
public boolean contains(final Object o) {
if (!(o instanceof OMVRBTreeEntry))
return false;
final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o;
final K key = entry.getKey();
if (!inRange(key))
return false;
V nodeValue = m.get(key);
return nodeValue != null && valEquals(nodeValue, entry.getValue());
}
@Override
public boolean remove(final Object o) {
if (!(o instanceof OMVRBTreeEntry))
return false;
final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o;
final K key = entry.getKey();
if (!inRange(key))
return false;
final OMVRBTreeEntry<K, V> node = m.getEntry(key, PartialSearchMode.NONE);
if (node != null && valEquals(node.getValue(), entry.getValue())) {
m.deleteEntry(node);
return true;
}
return false;
}
}
/**
* Iterators for SubMaps
*/
abstract class SubMapIterator<T> implements OLazyIterator<T> {
OMVRBTreeEntryPosition<K, V> lastReturned;
OMVRBTreeEntryPosition<K, V> next;
final K fenceKey;
int expectedModCount;
SubMapIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) {
expectedModCount = m.modCount;
lastReturned = null;
next = first;
fenceKey = fence == null ? null : fence.getKey();
}
public final boolean hasNext() {
if (next != null) {
final K k = next.getKey();
return k != fenceKey && !k.equals(fenceKey);
}
return false;
}
final OMVRBTreeEntryPosition<K, V> nextEntry() {
final OMVRBTreeEntryPosition<K, V> e;
if (next != null)
e = new OMVRBTreeEntryPosition<K, V>(next);
else
e = null;
if (e == null || e.entry == null)
throw new NoSuchElementException();
final K k = e.getKey();
if (k == fenceKey || k.equals(fenceKey))
throw new NoSuchElementException();
if (m.modCount != expectedModCount)
throw new ConcurrentModificationException();
next.assign(OMVRBTree.next(e));
lastReturned = e;
return e;
}
final OMVRBTreeEntryPosition<K, V> prevEntry() {
final OMVRBTreeEntryPosition<K, V> e;
if (next != null)
e = new OMVRBTreeEntryPosition<K, V>(next);
else
e = null;
if (e == null || e.entry == null)
throw new NoSuchElementException();
final K k = e.getKey();
if (k == fenceKey || k.equals(fenceKey))
throw new NoSuchElementException();
if (m.modCount != expectedModCount)
throw new ConcurrentModificationException();
next.assign(OMVRBTree.previous(e));
lastReturned = e;
return e;
}
final public T update(final T iValue) {
if (lastReturned == null)
throw new IllegalStateException();
if (m.modCount != expectedModCount)
throw new ConcurrentModificationException();
return (T) lastReturned.entry.setValue((V) iValue);
}
final void removeAscending() {
if (lastReturned == null)
throw new IllegalStateException();
if (m.modCount != expectedModCount)
throw new ConcurrentModificationException();
// deleted entries are replaced by their successors
if (lastReturned.entry.getLeft() != null && lastReturned.entry.getRight() != null)
next = lastReturned;
m.deleteEntry(lastReturned.entry);
lastReturned = null;
expectedModCount = m.modCount;
}
final void removeDescending() {
if (lastReturned == null)
throw new IllegalStateException();
if (m.modCount != expectedModCount)
throw new ConcurrentModificationException();
m.deleteEntry(lastReturned.entry);
lastReturned = null;
expectedModCount = m.modCount;
}
}
final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K, V>> {
SubMapEntryIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) {
super(first, fence);
}
public Map.Entry<K, V> next() {
final Map.Entry<K, V> e = OMVRBTree.exportEntry(next);
nextEntry();
return e;
}
public void remove() {
removeAscending();
}
}
final class SubMapKeyIterator extends SubMapIterator<K> {
SubMapKeyIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) {
super(first, fence);
}
public K next() {
return nextEntry().getKey();
}
public void remove() {
removeAscending();
}
}
final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K, V>> {
DescendingSubMapEntryIterator(final OMVRBTreeEntryPosition<K, V> last, final OMVRBTreeEntryPosition<K, V> fence) {
super(last, fence);
}
public Map.Entry<K, V> next() {
final Map.Entry<K, V> e = OMVRBTree.exportEntry(next);
prevEntry();
return e;
}
public void remove() {
removeDescending();
}
}
final class DescendingSubMapKeyIterator extends SubMapIterator<K> {
DescendingSubMapKeyIterator(final OMVRBTreeEntryPosition<K, V> last, final OMVRBTreeEntryPosition<K, V> fence) {
super(last, fence);
}
public K next() {
return prevEntry().getKey();
}
public void remove() {
removeDescending();
}
}
}
/**
* @serial include
*/
static final class AscendingSubMap<K, V> extends NavigableSubMap<K, V> {
private static final long serialVersionUID = 912986545866124060L;
AscendingSubMap(final OMVRBTree<K, V> m, final boolean fromStart, final K lo, final boolean loInclusive, final boolean toEnd,
K hi, final boolean hiInclusive) {
super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
}
public Comparator<? super K> comparator() {
return m.comparator();
}
public ONavigableMap<K, V> subMap(final K fromKey, final boolean fromInclusive, final K toKey, final boolean toInclusive) {
if (!inRange(fromKey, fromInclusive))
throw new IllegalArgumentException("fromKey out of range");
if (!inRange(toKey, toInclusive))
throw new IllegalArgumentException("toKey out of range");
return new AscendingSubMap<K, V>(m, false, fromKey, fromInclusive, false, toKey, toInclusive);
}
public ONavigableMap<K, V> headMap(final K toKey, final boolean inclusive) {
if (!inRange(toKey, inclusive))
throw new IllegalArgumentException("toKey out of range");
return new AscendingSubMap<K, V>(m, fromStart, lo, loInclusive, false, toKey, inclusive);
}
public ONavigableMap<K, V> tailMap(final K fromKey, final boolean inclusive) {
if (!inRange(fromKey, inclusive))
throw new IllegalArgumentException("fromKey out of range");
return new AscendingSubMap<K, V>(m, false, fromKey, inclusive, toEnd, hi, hiInclusive);
}
public ONavigableMap<K, V> descendingMap() {
ONavigableMap<K, V> mv = descendingMapView;
return (mv != null) ? mv : (descendingMapView = new DescendingSubMap<K, V>(m, fromStart, lo, loInclusive, toEnd, hi,
hiInclusive));
}
@Override
OLazyIterator<K> keyIterator() {
return new SubMapKeyIterator(absLowest(), absHighFence());
}
@Override
OLazyIterator<K> descendingKeyIterator() {
return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
}
final class AscendingEntrySetView extends EntrySetView {
@Override
public Iterator<Map.Entry<K, V>> iterator() {
return new SubMapEntryIterator(absLowest(), absHighFence());
}
}
@Override
public Set<Map.Entry<K, V>> entrySet() {
EntrySetView es = entrySetView;
return (es != null) ? es : new AscendingEntrySetView();
}
@Override
OMVRBTreeEntry<K, V> subLowest() {
return absLowest().entry;
}
@Override
OMVRBTreeEntry<K, V> subHighest() {
return absHighest().entry;
}
@Override
OMVRBTreeEntry<K, V> subCeiling(final K key) {
return absCeiling(key).entry;
}
@Override
OMVRBTreeEntry<K, V> subHigher(final K key) {
return absHigher(key).entry;
}
@Override
OMVRBTreeEntry<K, V> subFloor(final K key) {
return absFloor(key).entry;
}
@Override
OMVRBTreeEntry<K, V> subLower(final K key) {
return absLower(key).entry;
}
}
/**
* @serial include
*/
static final class DescendingSubMap<K, V> extends NavigableSubMap<K, V> {
private static final long serialVersionUID = 912986545866120460L;
private final Comparator<? super K> reverseComparator = Collections.reverseOrder(m.comparator);
DescendingSubMap(final OMVRBTree<K, V> m, final boolean fromStart, final K lo, final boolean loInclusive, final boolean toEnd,
final K hi, final boolean hiInclusive) {
super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
}
public Comparator<? super K> comparator() {
return reverseComparator;
}
public ONavigableMap<K, V> subMap(final K fromKey, final boolean fromInclusive, final K toKey, final boolean toInclusive) {
if (!inRange(fromKey, fromInclusive))
throw new IllegalArgumentException("fromKey out of range");
if (!inRange(toKey, toInclusive))
throw new IllegalArgumentException("toKey out of range");
return new DescendingSubMap<K, V>(m, false, toKey, toInclusive, false, fromKey, fromInclusive);
}
public ONavigableMap<K, V> headMap(final K toKey, final boolean inclusive) {
if (!inRange(toKey, inclusive))
throw new IllegalArgumentException("toKey out of range");
return new DescendingSubMap<K, V>(m, false, toKey, inclusive, toEnd, hi, hiInclusive);
}
public ONavigableMap<K, V> tailMap(final K fromKey, final boolean inclusive) {
if (!inRange(fromKey, inclusive))
throw new IllegalArgumentException("fromKey out of range");
return new DescendingSubMap<K, V>(m, fromStart, lo, loInclusive, false, fromKey, inclusive);
}
public ONavigableMap<K, V> descendingMap() {
ONavigableMap<K, V> mv = descendingMapView;
return (mv != null) ? mv : (descendingMapView = new AscendingSubMap<K, V>(m, fromStart, lo, loInclusive, toEnd, hi,
hiInclusive));
}
@Override
OLazyIterator<K> keyIterator() {
return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
}
@Override
OLazyIterator<K> descendingKeyIterator() {
return new SubMapKeyIterator(absLowest(), absHighFence());
}
final class DescendingEntrySetView extends EntrySetView {
@Override
public Iterator<Map.Entry<K, V>> iterator() {
return new DescendingSubMapEntryIterator(absHighest(), absLowFence());
}
}
@Override
public Set<Map.Entry<K, V>> entrySet() {
EntrySetView es = entrySetView;
return (es != null) ? es : new DescendingEntrySetView();
}
@Override
OMVRBTreeEntry<K, V> subLowest() {
return absHighest().entry;
}
@Override
OMVRBTreeEntry<K, V> subHighest() {
return absLowest().entry;
}
@Override
OMVRBTreeEntry<K, V> subCeiling(final K key) {
return absFloor(key).entry;
}
@Override
OMVRBTreeEntry<K, V> subHigher(final K key) {
return absLower(key).entry;
}
@Override
OMVRBTreeEntry<K, V> subFloor(final K key) {
return absCeiling(key).entry;
}
@Override
OMVRBTreeEntry<K, V> subLower(final K key) {
return absHigher(key).entry;
}
}
// Red-black mechanics
public static final boolean RED = false;
public static final boolean BLACK = true;
/**
* Node in the Tree. Doubles as a means to pass key-value pairs back to user (see Map.Entry).
*/
/**
* Returns the first Entry in the OMVRBTree (according to the OMVRBTree's key-sort function). Returns null if the OMVRBTree is
* empty.
*/
public OMVRBTreeEntry<K, V> getFirstEntry() {
OMVRBTreeEntry<K, V> p = root;
if (p != null) {
if (p.getSize() > 0)
pageIndex = 0;
while (p.getLeft() != null)
p = p.getLeft();
}
return p;
}
/**
* Returns the last Entry in the OMVRBTree (according to the OMVRBTree's key-sort function). Returns null if the OMVRBTree is
* empty.
*/
protected OMVRBTreeEntry<K, V> getLastEntry() {
OMVRBTreeEntry<K, V> p = root;
if (p != null)
while (p.getRight() != null)
p = p.getRight();
if (p != null)
pageIndex = p.getSize() - 1;
return p;
}
public static <K, V> OMVRBTreeEntry<K, V> successor(final OMVRBTreeEntryPosition<K, V> t) {
t.entry.getTree().setPageIndex(t.position);
return successor(t.entry);
}
/**
* Returns the successor of the specified Entry, or null if no such.
*/
public static <K, V> OMVRBTreeEntry<K, V> successor(final OMVRBTreeEntry<K, V> t) {
if (t == null)
return null;
OMVRBTreeEntry<K, V> p = null;
if (t.getRight() != null) {
p = t.getRight();
while (p.getLeft() != null)
p = p.getLeft();
} else {
p = t.getParent();
OMVRBTreeEntry<K, V> ch = t;
while (p != null && ch == p.getRight()) {
ch = p;
p = p.getParent();
}
}
return p;
}
public static <K, V> OMVRBTreeEntry<K, V> next(final OMVRBTreeEntryPosition<K, V> t) {
t.entry.getTree().setPageIndex(t.position);
return next(t.entry);
}
/**
* Returns the next item of the tree.
*/
public static <K, V> OMVRBTreeEntry<K, V> next(final OMVRBTreeEntry<K, V> t) {
if (t == null)
return null;
final OMVRBTreeEntry<K, V> succ;
if (t.tree.pageIndex < t.getSize() - 1) {
// ITERATE INSIDE THE NODE
succ = t;
t.tree.pageIndex++;
} else {
// GET THE NEXT NODE
succ = OMVRBTree.successor(t);
t.tree.pageIndex = 0;
}
return succ;
}
public static <K, V> OMVRBTreeEntry<K, V> predecessor(final OMVRBTreeEntryPosition<K, V> t) {
t.entry.getTree().setPageIndex(t.position);
return predecessor(t.entry);
}
/**
* Returns the predecessor of the specified Entry, or null if no such.
*/
public static <K, V> OMVRBTreeEntry<K, V> predecessor(final OMVRBTreeEntry<K, V> t) {
if (t == null)
return null;
else if (t.getLeft() != null) {
OMVRBTreeEntry<K, V> p = t.getLeft();
while (p.getRight() != null)
p = p.getRight();
return p;
} else {
OMVRBTreeEntry<K, V> p = t.getParent();
Entry<K, V> ch = t;
while (p != null && ch == p.getLeft()) {
ch = p;
p = p.getParent();
}
return p;
}
}
public static <K, V> OMVRBTreeEntry<K, V> previous(final OMVRBTreeEntryPosition<K, V> t) {
t.entry.getTree().setPageIndex(t.position);
return previous(t.entry);
}
/**
* Returns the previous item of the tree.
*/
public static <K, V> OMVRBTreeEntry<K, V> previous(final OMVRBTreeEntry<K, V> t) {
if (t == null)
return null;
final int index = t.getTree().getPageIndex();
final OMVRBTreeEntry<K, V> prev;
if (index <= 0) {
prev = predecessor(t);
if (prev != null)
t.tree.pageIndex = prev.getSize() - 1;
else
t.tree.pageIndex = 0;
} else {
prev = t;
t.tree.pageIndex = index - 1;
}
return prev;
}
/**
* Balancing operations.
*
* Implementations of rebalancings during insertion and deletion are slightly different than the CLR version. Rather than using
* dummy nilnodes, we use a set of accessors that deal properly with null. They are used to avoid messiness surrounding nullness
* checks in the main algorithms.
*/
private static <K, V> boolean colorOf(final OMVRBTreeEntry<K, V> p) {
return (p == null ? BLACK : p.getColor());
}
private static <K, V> OMVRBTreeEntry<K, V> parentOf(final OMVRBTreeEntry<K, V> p) {
return (p == null ? null : p.getParent());
}
private static <K, V> void setColor(final OMVRBTreeEntry<K, V> p, final boolean c) {
if (p != null)
p.setColor(c);
}
private static <K, V> OMVRBTreeEntry<K, V> leftOf(final OMVRBTreeEntry<K, V> p) {
return (p == null) ? null : p.getLeft();
}
private static <K, V> OMVRBTreeEntry<K, V> rightOf(final OMVRBTreeEntry<K, V> p) {
return (p == null) ? null : p.getRight();
}
/** From CLR */
protected void rotateLeft(final OMVRBTreeEntry<K, V> p) {
if (p != null) {
OMVRBTreeEntry<K, V> r = p.getRight();
p.setRight(r.getLeft());
if (r.getLeft() != null)
r.getLeft().setParent(p);
r.setParent(p.getParent());
if (p.getParent() == null)
setRoot(r);
else if (p.getParent().getLeft() == p)
p.getParent().setLeft(r);
else
p.getParent().setRight(r);
p.setParent(r);
r.setLeft(p);
}
}
protected void setRoot(final OMVRBTreeEntry<K, V> iRoot) {
root = iRoot;
}
/** From CLR */
protected void rotateRight(final OMVRBTreeEntry<K, V> p) {
if (p != null) {
OMVRBTreeEntry<K, V> l = p.getLeft();
p.setLeft(l.getRight());
if (l.getRight() != null)
l.getRight().setParent(p);
l.setParent(p.getParent());
if (p.getParent() == null)
setRoot(l);
else if (p.getParent().getRight() == p)
p.getParent().setRight(l);
else
p.getParent().setLeft(l);
l.setRight(p);
p.setParent(l);
}
}
private OMVRBTreeEntry<K, V> grandparent(final OMVRBTreeEntry<K, V> n) {
return parentOf(parentOf(n));
}
private OMVRBTreeEntry<K, V> uncle(final OMVRBTreeEntry<K, V> n) {
if (parentOf(n) == leftOf(grandparent(n)))
return rightOf(grandparent(n));
else
return leftOf(grandparent(n));
}
private void fixAfterInsertion(final OMVRBTreeEntry<K, V> n) {
if (parentOf(n) == null)
setColor(n, BLACK);
else
insert_case2(n);
}
private void insert_case2(final OMVRBTreeEntry<K, V> n) {
if (colorOf(parentOf(n)) == BLACK)
return; /* Tree is still valid */
else
insert_case3(n);
}
private void insert_case3(final OMVRBTreeEntry<K, V> n) {
if (uncle(n) != null && colorOf(uncle(n)) == RED) {
setColor(parentOf(n), BLACK);
setColor(uncle(n), BLACK);
setColor(grandparent(n), RED);
fixAfterInsertion(grandparent(n));
} else
insert_case4(n);
}
private void insert_case4(OMVRBTreeEntry<K, V> n) {
if (n == rightOf(parentOf(n)) && parentOf(n) == leftOf(grandparent(n))) {
rotateLeft(parentOf(n));
n = leftOf(n);
} else if (n == leftOf(parentOf(n)) && parentOf(n) == rightOf(grandparent(n))) {
rotateRight(parentOf(n));
n = rightOf(n);
}
insert_case5(n);
}
private void insert_case5(final OMVRBTreeEntry<K, V> n) {
setColor(parentOf(n), BLACK);
setColor(grandparent(n), RED);
if (n == leftOf(parentOf(n)) && parentOf(n) == leftOf(grandparent(n))) {
rotateRight(grandparent(n));
} else {
rotateLeft(grandparent(n));
}
}
/**
* Delete node p, and then re-balance the tree.
*
* @param p
* node to delete
* @return
*/
OMVRBTreeEntry<K, V> deleteEntry(OMVRBTreeEntry<K, V> p) {
setSizeDelta(-1);
modCount++;
if (pageIndex > -1) {
// DELETE INSIDE THE NODE
p.remove();
if (p.getSize() > 0)
return p;
}
final OMVRBTreeEntry<K, V> next = successor(p);
// DELETE THE ENTIRE NODE, RE-BUILDING THE STRUCTURE
removeNode(p);
// RETURN NEXT NODE
return next;
}
/**
* Remove a node from the tree.
*
* @param p
* Node to remove
*
* @return Node that was removed. Passed and removed nodes may be different in case node to remove contains two children. In this
* case node successor will be found and removed but it's content will be copied to the node that was passed in method.
*/
protected OMVRBTreeEntry<K, V> removeNode(OMVRBTreeEntry<K, V> p) {
modCount++;
// If strictly internal, copy successor's element to p and then make p
// point to successor.
if (p.getLeft() != null && p.getRight() != null) {
OMVRBTreeEntry<K, V> s = next(p);
p.copyFrom(s);
p = s;
} // p has 2 children
// Start fixup at replacement node, if it exists.
final OMVRBTreeEntry<K, V> replacement = (p.getLeft() != null ? p.getLeft() : p.getRight());
if (replacement != null) {
// Link replacement to parent
replacement.setParent(p.getParent());
if (p.getParent() == null)
setRoot(replacement);
else if (p == p.getParent().getLeft())
p.getParent().setLeft(replacement);
else
p.getParent().setRight(replacement);
// Null out links so they are OK to use by fixAfterDeletion.
p.setLeft(null);
p.setRight(null);
p.setParent(null);
// Fix replacement
if (p.getColor() == BLACK)
fixAfterDeletion(replacement);
} else if (p.getParent() == null && size() == 0) { // return if we are the only node. Check the size to be sure the map is empty
clear();
} else { // No children. Use self as phantom replacement and unlink.
if (p.getColor() == BLACK)
fixAfterDeletion(p);
if (p.getParent() != null) {
if (p == p.getParent().getLeft())
p.getParent().setLeft(null);
else if (p == p.getParent().getRight())
p.getParent().setRight(null);
p.setParent(null);
}
}
return p;
}
/** From CLR */
private void fixAfterDeletion(OMVRBTreeEntry<K, V> x) {
while (x != root && colorOf(x) == BLACK) {
if (x == leftOf(parentOf(x))) {
OMVRBTreeEntry<K, V> sib = rightOf(parentOf(x));
if (colorOf(sib) == RED) {
setColor(sib, BLACK);
setColor(parentOf(x), RED);
rotateLeft(parentOf(x));
sib = rightOf(parentOf(x));
}
if (colorOf(leftOf(sib)) == BLACK && colorOf(rightOf(sib)) == BLACK) {
setColor(sib, RED);
x = parentOf(x);
} else {
if (colorOf(rightOf(sib)) == BLACK) {
setColor(leftOf(sib), BLACK);
setColor(sib, RED);
rotateRight(sib);
sib = rightOf(parentOf(x));
}
setColor(sib, colorOf(parentOf(x)));
setColor(parentOf(x), BLACK);
setColor(rightOf(sib), BLACK);
rotateLeft(parentOf(x));
x = root;
}
} else { // symmetric
OMVRBTreeEntry<K, V> sib = leftOf(parentOf(x));
if (colorOf(sib) == RED) {
setColor(sib, BLACK);
setColor(parentOf(x), RED);
rotateRight(parentOf(x));
sib = leftOf(parentOf(x));
}
if (x != null && colorOf(rightOf(sib)) == BLACK && colorOf(leftOf(sib)) == BLACK) {
setColor(sib, RED);
x = parentOf(x);
} else {
if (colorOf(leftOf(sib)) == BLACK) {
setColor(rightOf(sib), BLACK);
setColor(sib, RED);
rotateLeft(sib);
sib = leftOf(parentOf(x));
}
setColor(sib, colorOf(parentOf(x)));
setColor(parentOf(x), BLACK);
setColor(leftOf(sib), BLACK);
rotateRight(parentOf(x));
x = root;
}
}
}
setColor(x, BLACK);
}
/**
* Save the state of the <tt>OMVRBTree</tt> instance to a stream (i.e., serialize it).
*
* @serialData The <i>size</i> of the OMVRBTree (the number of key-value mappings) is emitted (int), followed by the key (Object)
* and value (Object) for each key-value mapping represented by the OMVRBTree. The key-value mappings are emitted in
* key-order (as determined by the OMVRBTree's Comparator, or by the keys' natural ordering if the OMVRBTree has no
* Comparator).
*/
private void writeObject(final ObjectOutputStream s) throws java.io.IOException {
// Write out the Comparator and any hidden stuff
s.defaultWriteObject();
// Write out size (number of Mappings)
s.writeInt(size());
// Write out keys and values (alternating)
for (Iterator<Map.Entry<K, V>> i = entrySet().iterator(); i.hasNext();) {
Entry<K, V> e = i.next();
s.writeObject(e.getKey());
s.writeObject(e.getValue());
}
}
/**
* Reconstitute the <tt>OMVRBTree</tt> instance from a stream (i.e., deserialize it).
*/
private void readObject(final java.io.ObjectInputStream s) throws IOException, ClassNotFoundException {
// Read in the Comparator and any hidden stuff
s.defaultReadObject();
// Read in size
setSize(s.readInt());
buildFromSorted(size(), null, s, null);
}
/** Intended to be called only from OTreeSet.readObject */
void readOTreeSet(int iSize, ObjectInputStream s, V defaultVal) throws java.io.IOException, ClassNotFoundException {
buildFromSorted(iSize, null, s, defaultVal);
}
/** Intended to be called only from OTreeSet.addAll */
void addAllForOTreeSet(SortedSet<? extends K> set, V defaultVal) {
try {
buildFromSorted(set.size(), set.iterator(), null, defaultVal);
} catch (java.io.IOException cannotHappen) {
} catch (ClassNotFoundException cannotHappen) {
}
}
/**
* Linear time tree building algorithm from sorted data. Can accept keys and/or values from iterator or stream. This leads to too
* many parameters, but seems better than alternatives. The four formats that this method accepts are:
*
* 1) An iterator of Map.Entries. (it != null, defaultVal == null). 2) An iterator of keys. (it != null, defaultVal != null). 3) A
* stream of alternating serialized keys and values. (it == null, defaultVal == null). 4) A stream of serialized keys. (it ==
* null, defaultVal != null).
*
* It is assumed that the comparator of the OMVRBTree is already set prior to calling this method.
*
* @param size
* the number of keys (or key-value pairs) to be read from the iterator or stream
* @param it
* If non-null, new entries are created from entries or keys read from this iterator.
* @param str
* If non-null, new entries are created from keys and possibly values read from this stream in serialized form. Exactly
* one of it and str should be non-null.
* @param defaultVal
* if non-null, this default value is used for each value in the map. If null, each value is read from iterator or
* stream, as described above.
* @throws IOException
* propagated from stream reads. This cannot occur if str is null.
* @throws ClassNotFoundException
* propagated from readObject. This cannot occur if str is null.
*/
private void buildFromSorted(final int size, final Iterator<?> it, final java.io.ObjectInputStream str, final V defaultVal)
throws java.io.IOException, ClassNotFoundException {
setSize(size);
root = buildFromSorted(0, 0, size - 1, computeRedLevel(size), it, str, defaultVal);
}
/**
* Recursive "helper method" that does the real work of the previous method. Identically named parameters have identical
* definitions. Additional parameters are documented below. It is assumed that the comparator and size fields of the OMVRBTree are
* already set prior to calling this method. (It ignores both fields.)
*
* @param level
* the current level of tree. Initial call should be 0.
* @param lo
* the first element index of this subtree. Initial should be 0.
* @param hi
* the last element index of this subtree. Initial should be size-1.
* @param redLevel
* the level at which nodes should be red. Must be equal to computeRedLevel for tree of this size.
*/
private final OMVRBTreeEntry<K, V> buildFromSorted(final int level, final int lo, final int hi, final int redLevel,
final Iterator<?> it, final java.io.ObjectInputStream str, final V defaultVal) throws java.io.IOException,
ClassNotFoundException {
/*
* Strategy: The root is the middlemost element. To get to it, we have to first recursively construct the entire left subtree,
* so as to grab all of its elements. We can then proceed with right subtree.
*
* The lo and hi arguments are the minimum and maximum indices to pull out of the iterator or stream for current subtree. They
* are not actually indexed, we just proceed sequentially, ensuring that items are extracted in corresponding order.
*/
if (hi < lo)
return null;
final int mid = (lo + hi) / 2;
OMVRBTreeEntry<K, V> left = null;
if (lo < mid)
left = buildFromSorted(level + 1, lo, mid - 1, redLevel, it, str, defaultVal);
// extract key and/or value from iterator or stream
K key;
V value;
if (it != null) {
if (defaultVal == null) {
OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) it.next();
key = entry.getKey();
value = entry.getValue();
} else {
key = (K) it.next();
value = defaultVal;
}
} else { // use stream
key = (K) str.readObject();
value = (defaultVal != null ? defaultVal : (V) str.readObject());
}
final OMVRBTreeEntry<K, V> middle = createEntry(key, value);
// color nodes in non-full bottom most level red
if (level == redLevel)
middle.setColor(RED);
if (left != null) {
middle.setLeft(left);
left.setParent(middle);
}
if (mid < hi) {
OMVRBTreeEntry<K, V> right = buildFromSorted(level + 1, mid + 1, hi, redLevel, it, str, defaultVal);
middle.setRight(right);
right.setParent(middle);
}
return middle;
}
/**
* Find the level down to which to assign all nodes BLACK. This is the last `full' level of the complete binary tree produced by
* buildTree. The remaining nodes are colored RED. (This makes a `nice' set of color assignments wrt future insertions.) This
* level number is computed by finding the number of splits needed to reach the zeroeth node. (The answer is ~lg(N), but in any
* case must be computed by same quick O(lg(N)) loop.)
*/
private static int computeRedLevel(final int sz) {
int level = 0;
for (int m = sz - 1; m >= 0; m = m / 2 - 1)
level++;
return level;
}
public int getPageIndex() {
return pageIndex;
}
public void setPageIndex(final int iPageIndex) {
pageIndex = iPageIndex;
}
private void init() {
}
public OMVRBTreeEntry<K, V> getRoot() {
return root;
}
protected void printInMemoryStructure(final OMVRBTreeEntry<K, V> iRootNode) {
printInMemoryNode("root", iRootNode, 0);
}
private void printInMemoryNode(final String iLabel, OMVRBTreeEntry<K, V> iNode, int iLevel) {
if (iNode == null)
return;
for (int i = 0; i < iLevel; ++i)
System.out.print(' ');
System.out.println(iLabel + ": " + iNode.toString() + " (" + (iNode.getColor() ? "B" : "R") + ")");
++iLevel;
printInMemoryNode(iLevel + ".left", iNode.getLeftInMemory(), iLevel);
printInMemoryNode(iLevel + ".right", iNode.getRightInMemory(), iLevel);
}
public void checkTreeStructure(final OMVRBTreeEntry<K, V> iRootNode) {
if (!runtimeCheckEnabled || iRootNode == null)
return;
int currPageIndex = pageIndex;
OMVRBTreeEntry<K, V> prevNode = null;
int i = 0;
for (OMVRBTreeEntry<K, V> e = iRootNode.getFirstInMemory(); e != null; e = e.getNextInMemory()) {
if (e.getSize() == 0)
OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Node %s has 0 items\n", e);
if (prevNode != null) {
if (prevNode.getTree() == null)
OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Freed record %d found in memory\n", i);
if (compare(e.getFirstKey(), e.getLastKey()) > 0) {
OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] begin key is > than last key\n", e.getFirstKey(),
e.getLastKey());
printInMemoryStructure(iRootNode);
}
if (compare(e.getFirstKey(), prevNode.getLastKey()) < 0) {
OLogManager.instance().error(this,
"[OMVRBTree.checkTreeStructure] Node %s starts with a key minor than the last key of the previous node %s\n", e,
prevNode);
printInMemoryStructure(e.getParentInMemory() != null ? e.getParentInMemory() : e);
}
}
if (e.getLeftInMemory() != null && e.getLeftInMemory() == e) {
OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Node %s has left that points to itself!\n", e);
printInMemoryStructure(iRootNode);
}
if (e.getRightInMemory() != null && e.getRightInMemory() == e) {
OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Node %s has right that points to itself!\n", e);
printInMemoryStructure(iRootNode);
}
if (e.getLeftInMemory() != null && e.getLeftInMemory() == e.getRightInMemory()) {
OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Node %s has left and right equals!\n", e);
printInMemoryStructure(iRootNode);
}
if (e.getParentInMemory() != null && e.getParentInMemory().getRightInMemory() != e
&& e.getParentInMemory().getLeftInMemory() != e) {
OLogManager.instance().error(this,
"[OMVRBTree.checkTreeStructure] Node %s is the children of node %s but the cross-reference is missed!\n", e,
e.getParentInMemory());
printInMemoryStructure(iRootNode);
}
prevNode = e;
++i;
}
pageIndex = currPageIndex;
}
public boolean isRuntimeCheckEnabled() {
return runtimeCheckEnabled;
}
public void setChecks(boolean checks) {
this.runtimeCheckEnabled = checks;
}
public void setRuntimeCheckEnabled(boolean runtimeCheckEnabled) {
this.runtimeCheckEnabled = runtimeCheckEnabled;
}
public boolean isDebug() {
return debug;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
protected OMVRBTreeEntry<K, V> getLastSearchNodeForSameKey(final Object key) {
if (key != null && lastSearchKey != null) {
if (key instanceof OCompositeKey)
return key.equals(lastSearchKey) ? lastSearchNode : null;
if (comparator != null)
return comparator.compare((K) key, (K) lastSearchKey) == 0 ? lastSearchNode : null;
else
try {
return ((Comparable<? super K>) key).compareTo((K) lastSearchKey) == 0 ? lastSearchNode : null;
} catch (Exception e) {
// IGNORE IT
}
}
return null;
}
protected OMVRBTreeEntry<K, V> setLastSearchNode(final Object iKey, final OMVRBTreeEntry<K, V> iNode) {
lastSearchKey = iKey;
lastSearchNode = iNode;
lastSearchFound = iNode != null ? iNode.tree.pageItemFound : false;
lastSearchIndex = iNode != null ? iNode.tree.pageIndex : -1;
return iNode;
}
protected void searchNodeCallback() {
}
protected void setSizeDelta(final int iDelta) {
setSize(size() + iDelta);
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
12 | static final class AscendingSubMap<K, V> extends NavigableSubMap<K, V> {
private static final long serialVersionUID = 912986545866124060L;
AscendingSubMap(final OMVRBTree<K, V> m, final boolean fromStart, final K lo, final boolean loInclusive, final boolean toEnd,
K hi, final boolean hiInclusive) {
super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
}
public Comparator<? super K> comparator() {
return m.comparator();
}
public ONavigableMap<K, V> subMap(final K fromKey, final boolean fromInclusive, final K toKey, final boolean toInclusive) {
if (!inRange(fromKey, fromInclusive))
throw new IllegalArgumentException("fromKey out of range");
if (!inRange(toKey, toInclusive))
throw new IllegalArgumentException("toKey out of range");
return new AscendingSubMap<K, V>(m, false, fromKey, fromInclusive, false, toKey, toInclusive);
}
public ONavigableMap<K, V> headMap(final K toKey, final boolean inclusive) {
if (!inRange(toKey, inclusive))
throw new IllegalArgumentException("toKey out of range");
return new AscendingSubMap<K, V>(m, fromStart, lo, loInclusive, false, toKey, inclusive);
}
public ONavigableMap<K, V> tailMap(final K fromKey, final boolean inclusive) {
if (!inRange(fromKey, inclusive))
throw new IllegalArgumentException("fromKey out of range");
return new AscendingSubMap<K, V>(m, false, fromKey, inclusive, toEnd, hi, hiInclusive);
}
public ONavigableMap<K, V> descendingMap() {
ONavigableMap<K, V> mv = descendingMapView;
return (mv != null) ? mv : (descendingMapView = new DescendingSubMap<K, V>(m, fromStart, lo, loInclusive, toEnd, hi,
hiInclusive));
}
@Override
OLazyIterator<K> keyIterator() {
return new SubMapKeyIterator(absLowest(), absHighFence());
}
@Override
OLazyIterator<K> descendingKeyIterator() {
return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
}
final class AscendingEntrySetView extends EntrySetView {
@Override
public Iterator<Map.Entry<K, V>> iterator() {
return new SubMapEntryIterator(absLowest(), absHighFence());
}
}
@Override
public Set<Map.Entry<K, V>> entrySet() {
EntrySetView es = entrySetView;
return (es != null) ? es : new AscendingEntrySetView();
}
@Override
OMVRBTreeEntry<K, V> subLowest() {
return absLowest().entry;
}
@Override
OMVRBTreeEntry<K, V> subHighest() {
return absHighest().entry;
}
@Override
OMVRBTreeEntry<K, V> subCeiling(final K key) {
return absCeiling(key).entry;
}
@Override
OMVRBTreeEntry<K, V> subHigher(final K key) {
return absHigher(key).entry;
}
@Override
OMVRBTreeEntry<K, V> subFloor(final K key) {
return absFloor(key).entry;
}
@Override
OMVRBTreeEntry<K, V> subLower(final K key) {
return absLower(key).entry;
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
13 | final class AscendingEntrySetView extends EntrySetView {
@Override
public Iterator<Map.Entry<K, V>> iterator() {
return new SubMapEntryIterator(absLowest(), absHighFence());
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
14 | final class DescendingKeyIterator extends AbstractEntryIterator<K, V, K> {
DescendingKeyIterator(final OMVRBTreeEntry<K, V> first) {
super(first);
}
public K next() {
return prevEntry().getKey();
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
15 | static final class DescendingSubMap<K, V> extends NavigableSubMap<K, V> {
private static final long serialVersionUID = 912986545866120460L;
private final Comparator<? super K> reverseComparator = Collections.reverseOrder(m.comparator);
DescendingSubMap(final OMVRBTree<K, V> m, final boolean fromStart, final K lo, final boolean loInclusive, final boolean toEnd,
final K hi, final boolean hiInclusive) {
super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
}
public Comparator<? super K> comparator() {
return reverseComparator;
}
public ONavigableMap<K, V> subMap(final K fromKey, final boolean fromInclusive, final K toKey, final boolean toInclusive) {
if (!inRange(fromKey, fromInclusive))
throw new IllegalArgumentException("fromKey out of range");
if (!inRange(toKey, toInclusive))
throw new IllegalArgumentException("toKey out of range");
return new DescendingSubMap<K, V>(m, false, toKey, toInclusive, false, fromKey, fromInclusive);
}
public ONavigableMap<K, V> headMap(final K toKey, final boolean inclusive) {
if (!inRange(toKey, inclusive))
throw new IllegalArgumentException("toKey out of range");
return new DescendingSubMap<K, V>(m, false, toKey, inclusive, toEnd, hi, hiInclusive);
}
public ONavigableMap<K, V> tailMap(final K fromKey, final boolean inclusive) {
if (!inRange(fromKey, inclusive))
throw new IllegalArgumentException("fromKey out of range");
return new DescendingSubMap<K, V>(m, fromStart, lo, loInclusive, false, fromKey, inclusive);
}
public ONavigableMap<K, V> descendingMap() {
ONavigableMap<K, V> mv = descendingMapView;
return (mv != null) ? mv : (descendingMapView = new AscendingSubMap<K, V>(m, fromStart, lo, loInclusive, toEnd, hi,
hiInclusive));
}
@Override
OLazyIterator<K> keyIterator() {
return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
}
@Override
OLazyIterator<K> descendingKeyIterator() {
return new SubMapKeyIterator(absLowest(), absHighFence());
}
final class DescendingEntrySetView extends EntrySetView {
@Override
public Iterator<Map.Entry<K, V>> iterator() {
return new DescendingSubMapEntryIterator(absHighest(), absLowFence());
}
}
@Override
public Set<Map.Entry<K, V>> entrySet() {
EntrySetView es = entrySetView;
return (es != null) ? es : new DescendingEntrySetView();
}
@Override
OMVRBTreeEntry<K, V> subLowest() {
return absHighest().entry;
}
@Override
OMVRBTreeEntry<K, V> subHighest() {
return absLowest().entry;
}
@Override
OMVRBTreeEntry<K, V> subCeiling(final K key) {
return absFloor(key).entry;
}
@Override
OMVRBTreeEntry<K, V> subHigher(final K key) {
return absLower(key).entry;
}
@Override
OMVRBTreeEntry<K, V> subFloor(final K key) {
return absCeiling(key).entry;
}
@Override
OMVRBTreeEntry<K, V> subLower(final K key) {
return absHigher(key).entry;
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
16 | final class DescendingEntrySetView extends EntrySetView {
@Override
public Iterator<Map.Entry<K, V>> iterator() {
return new DescendingSubMapEntryIterator(absHighest(), absLowFence());
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
17 | final class EntryIterator extends AbstractEntryIterator<K, V, Map.Entry<K, V>> {
EntryIterator(final OMVRBTreeEntry<K, V> first) {
super(first);
}
public Map.Entry<K, V> next() {
return nextEntry();
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
18 | public class EntrySet extends AbstractSet<Map.Entry<K, V>> {
@Override
public Iterator<Map.Entry<K, V>> iterator() {
return new EntryIterator(getFirstEntry());
}
public Iterator<Map.Entry<K, V>> inverseIterator() {
return new InverseEntryIterator(getLastEntry());
}
@Override
public boolean contains(final Object o) {
if (!(o instanceof Map.Entry))
return false;
OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o;
final V value = entry.getValue();
final V p = get(entry.getKey());
return p != null && valEquals(p, value);
}
@Override
public boolean remove(final Object o) {
if (!(o instanceof Map.Entry))
return false;
final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o;
final V value = entry.getValue();
OMVRBTreeEntry<K, V> p = getEntry(entry.getKey(), PartialSearchMode.NONE);
if (p != null && valEquals(p.getValue(), value)) {
deleteEntry(p);
return true;
}
return false;
}
@Override
public int size() {
return OMVRBTree.this.size();
}
@Override
public void clear() {
OMVRBTree.this.clear();
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
19 | final class InverseEntryIterator extends AbstractEntryIterator<K, V, Map.Entry<K, V>> {
InverseEntryIterator(final OMVRBTreeEntry<K, V> last) {
super(last);
// we have to set ourselves after current index to make iterator work
if (last != null) {
pageIndex = last.getTree().getPageIndex() + 1;
}
}
public Map.Entry<K, V> next() {
return prevEntry();
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
20 | final class KeyIterator extends AbstractEntryIterator<K, V, K> {
KeyIterator(final OMVRBTreeEntry<K, V> first) {
super(first);
}
@Override
public K next() {
return nextKey();
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
21 | @SuppressWarnings("rawtypes")
static final class KeySet<E> extends AbstractSet<E> implements ONavigableSet<E> {
private final ONavigableMap<E, Object> m;
KeySet(ONavigableMap<E, Object> map) {
m = map;
}
@Override
public OLazyIterator<E> iterator() {
if (m instanceof OMVRBTree)
return ((OMVRBTree<E, Object>) m).keyIterator();
else
return (((OMVRBTree.NavigableSubMap) m).keyIterator());
}
public OLazyIterator<E> descendingIterator() {
if (m instanceof OMVRBTree)
return ((OMVRBTree<E, Object>) m).descendingKeyIterator();
else
return (((OMVRBTree.NavigableSubMap) m).descendingKeyIterator());
}
@Override
public int size() {
return m.size();
}
@Override
public boolean isEmpty() {
return m.isEmpty();
}
@Override
public boolean contains(final Object o) {
return m.containsKey(o);
}
@Override
public void clear() {
m.clear();
}
public E lower(final E e) {
return m.lowerKey(e);
}
public E floor(final E e) {
return m.floorKey(e);
}
public E ceiling(final E e) {
return m.ceilingKey(e);
}
public E higher(final E e) {
return m.higherKey(e);
}
public E first() {
return m.firstKey();
}
public E last() {
return m.lastKey();
}
public Comparator<? super E> comparator() {
return m.comparator();
}
public E pollFirst() {
final Map.Entry<E, Object> e = m.pollFirstEntry();
return e == null ? null : e.getKey();
}
public E pollLast() {
final Map.Entry<E, Object> e = m.pollLastEntry();
return e == null ? null : e.getKey();
}
@Override
public boolean remove(final Object o) {
final int oldSize = size();
m.remove(o);
return size() != oldSize;
}
public ONavigableSet<E> subSet(final E fromElement, final boolean fromInclusive, final E toElement, final boolean toInclusive) {
return new OMVRBTreeSet<E>(m.subMap(fromElement, fromInclusive, toElement, toInclusive));
}
public ONavigableSet<E> headSet(final E toElement, final boolean inclusive) {
return new OMVRBTreeSet<E>(m.headMap(toElement, inclusive));
}
public ONavigableSet<E> tailSet(final E fromElement, final boolean inclusive) {
return new OMVRBTreeSet<E>(m.tailMap(fromElement, inclusive));
}
public SortedSet<E> subSet(final E fromElement, final E toElement) {
return subSet(fromElement, true, toElement, false);
}
public SortedSet<E> headSet(final E toElement) {
return headSet(toElement, false);
}
public SortedSet<E> tailSet(final E fromElement) {
return tailSet(fromElement, true);
}
public ONavigableSet<E> descendingSet() {
return new OMVRBTreeSet<E>(m.descendingMap());
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
22 | static abstract class NavigableSubMap<K, V> extends AbstractMap<K, V> implements ONavigableMap<K, V>, java.io.Serializable {
/**
* The backing map.
*/
final OMVRBTree<K, V> m;
/**
* Endpoints are represented as triples (fromStart, lo, loInclusive) and (toEnd, hi, hiInclusive). If fromStart is true, then
* the low (absolute) bound is the start of the backing map, and the other values are ignored. Otherwise, if loInclusive is
* true, lo is the inclusive bound, else lo is the exclusive bound. Similarly for the upper bound.
*/
final K lo, hi;
final boolean fromStart, toEnd;
final boolean loInclusive, hiInclusive;
NavigableSubMap(final OMVRBTree<K, V> m, final boolean fromStart, K lo, final boolean loInclusive, final boolean toEnd, K hi,
final boolean hiInclusive) {
if (!fromStart && !toEnd) {
if (m.compare(lo, hi) > 0)
throw new IllegalArgumentException("fromKey > toKey");
} else {
if (!fromStart) // type check
m.compare(lo, lo);
if (!toEnd)
m.compare(hi, hi);
}
this.m = m;
this.fromStart = fromStart;
this.lo = lo;
this.loInclusive = loInclusive;
this.toEnd = toEnd;
this.hi = hi;
this.hiInclusive = hiInclusive;
}
// internal utilities
final boolean tooLow(final Object key) {
if (!fromStart) {
int c = m.compare(key, lo);
if (c < 0 || (c == 0 && !loInclusive))
return true;
}
return false;
}
final boolean tooHigh(final Object key) {
if (!toEnd) {
int c = m.compare(key, hi);
if (c > 0 || (c == 0 && !hiInclusive))
return true;
}
return false;
}
final boolean inRange(final Object key) {
return !tooLow(key) && !tooHigh(key);
}
final boolean inClosedRange(final Object key) {
return (fromStart || m.compare(key, lo) >= 0) && (toEnd || m.compare(hi, key) >= 0);
}
final boolean inRange(final Object key, final boolean inclusive) {
return inclusive ? inRange(key) : inClosedRange(key);
}
/*
* Absolute versions of relation operations. Subclasses map to these using like-named "sub" versions that invert senses for
* descending maps
*/
final OMVRBTreeEntryPosition<K, V> absLowest() {
OMVRBTreeEntry<K, V> e = (fromStart ? m.getFirstEntry() : (loInclusive ? m.getCeilingEntry(lo,
PartialSearchMode.LOWEST_BOUNDARY) : m.getHigherEntry(lo)));
return (e == null || tooHigh(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e);
}
final OMVRBTreeEntryPosition<K, V> absHighest() {
OMVRBTreeEntry<K, V> e = (toEnd ? m.getLastEntry() : (hiInclusive ? m.getFloorEntry(hi, PartialSearchMode.HIGHEST_BOUNDARY)
: m.getLowerEntry(hi)));
return (e == null || tooLow(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e);
}
final OMVRBTreeEntryPosition<K, V> absCeiling(K key) {
if (tooLow(key))
return absLowest();
OMVRBTreeEntry<K, V> e = m.getCeilingEntry(key, PartialSearchMode.NONE);
return (e == null || tooHigh(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e);
}
final OMVRBTreeEntryPosition<K, V> absHigher(K key) {
if (tooLow(key))
return absLowest();
OMVRBTreeEntry<K, V> e = m.getHigherEntry(key);
return (e == null || tooHigh(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e);
}
final OMVRBTreeEntryPosition<K, V> absFloor(K key) {
if (tooHigh(key))
return absHighest();
OMVRBTreeEntry<K, V> e = m.getFloorEntry(key, PartialSearchMode.NONE);
return (e == null || tooLow(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e);
}
final OMVRBTreeEntryPosition<K, V> absLower(K key) {
if (tooHigh(key))
return absHighest();
OMVRBTreeEntry<K, V> e = m.getLowerEntry(key);
return (e == null || tooLow(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e);
}
/** Returns the absolute high fence for ascending traversal */
final OMVRBTreeEntryPosition<K, V> absHighFence() {
return (toEnd ? null : new OMVRBTreeEntryPosition<K, V>(hiInclusive ? m.getHigherEntry(hi) : m.getCeilingEntry(hi,
PartialSearchMode.LOWEST_BOUNDARY)));
}
/** Return the absolute low fence for descending traversal */
final OMVRBTreeEntryPosition<K, V> absLowFence() {
return (fromStart ? null : new OMVRBTreeEntryPosition<K, V>(loInclusive ? m.getLowerEntry(lo) : m.getFloorEntry(lo,
PartialSearchMode.HIGHEST_BOUNDARY)));
}
// Abstract methods defined in ascending vs descending classes
// These relay to the appropriate absolute versions
abstract OMVRBTreeEntry<K, V> subLowest();
abstract OMVRBTreeEntry<K, V> subHighest();
abstract OMVRBTreeEntry<K, V> subCeiling(K key);
abstract OMVRBTreeEntry<K, V> subHigher(K key);
abstract OMVRBTreeEntry<K, V> subFloor(K key);
abstract OMVRBTreeEntry<K, V> subLower(K key);
/** Returns ascending iterator from the perspective of this submap */
abstract OLazyIterator<K> keyIterator();
/** Returns descending iterator from the perspective of this submap */
abstract OLazyIterator<K> descendingKeyIterator();
// public methods
@Override
public boolean isEmpty() {
return (fromStart && toEnd) ? m.isEmpty() : entrySet().isEmpty();
}
@Override
public int size() {
return (fromStart && toEnd) ? m.size() : entrySet().size();
}
@Override
public final boolean containsKey(Object key) {
return inRange(key) && m.containsKey(key);
}
@Override
public final V put(K key, V value) {
if (!inRange(key))
throw new IllegalArgumentException("key out of range");
return m.put(key, value);
}
@Override
public final V get(Object key) {
return !inRange(key) ? null : m.get(key);
}
@Override
public final V remove(Object key) {
return !inRange(key) ? null : m.remove(key);
}
public final Map.Entry<K, V> ceilingEntry(K key) {
return exportEntry(subCeiling(key));
}
public final K ceilingKey(K key) {
return keyOrNull(subCeiling(key));
}
public final Map.Entry<K, V> higherEntry(K key) {
return exportEntry(subHigher(key));
}
public final K higherKey(K key) {
return keyOrNull(subHigher(key));
}
public final Map.Entry<K, V> floorEntry(K key) {
return exportEntry(subFloor(key));
}
public final K floorKey(K key) {
return keyOrNull(subFloor(key));
}
public final Map.Entry<K, V> lowerEntry(K key) {
return exportEntry(subLower(key));
}
public final K lowerKey(K key) {
return keyOrNull(subLower(key));
}
public final K firstKey() {
return key(subLowest());
}
public final K lastKey() {
return key(subHighest());
}
public final Map.Entry<K, V> firstEntry() {
return exportEntry(subLowest());
}
public final Map.Entry<K, V> lastEntry() {
return exportEntry(subHighest());
}
public final Map.Entry<K, V> pollFirstEntry() {
OMVRBTreeEntry<K, V> e = subLowest();
Map.Entry<K, V> result = exportEntry(e);
if (e != null)
m.deleteEntry(e);
return result;
}
public final Map.Entry<K, V> pollLastEntry() {
OMVRBTreeEntry<K, V> e = subHighest();
Map.Entry<K, V> result = exportEntry(e);
if (e != null)
m.deleteEntry(e);
return result;
}
// Views
transient ONavigableMap<K, V> descendingMapView = null;
transient EntrySetView entrySetView = null;
transient KeySet<K> navigableKeySetView = null;
@SuppressWarnings("rawtypes")
public final ONavigableSet<K> navigableKeySet() {
KeySet<K> nksv = navigableKeySetView;
return (nksv != null) ? nksv : (navigableKeySetView = new OMVRBTree.KeySet(this));
}
@Override
public final Set<K> keySet() {
return navigableKeySet();
}
public ONavigableSet<K> descendingKeySet() {
return descendingMap().navigableKeySet();
}
public final SortedMap<K, V> subMap(final K fromKey, final K toKey) {
return subMap(fromKey, true, toKey, false);
}
public final SortedMap<K, V> headMap(final K toKey) {
return headMap(toKey, false);
}
public final SortedMap<K, V> tailMap(final K fromKey) {
return tailMap(fromKey, true);
}
// View classes
abstract class EntrySetView extends AbstractSet<Map.Entry<K, V>> {
private transient int size = -1, sizeModCount;
@Override
public int size() {
if (fromStart && toEnd)
return m.size();
if (size == -1 || sizeModCount != m.modCount) {
sizeModCount = m.modCount;
size = 0;
Iterator<?> i = iterator();
while (i.hasNext()) {
size++;
i.next();
}
}
return size;
}
@Override
public boolean isEmpty() {
OMVRBTreeEntryPosition<K, V> n = absLowest();
return n == null || tooHigh(n.getKey());
}
@Override
public boolean contains(final Object o) {
if (!(o instanceof OMVRBTreeEntry))
return false;
final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o;
final K key = entry.getKey();
if (!inRange(key))
return false;
V nodeValue = m.get(key);
return nodeValue != null && valEquals(nodeValue, entry.getValue());
}
@Override
public boolean remove(final Object o) {
if (!(o instanceof OMVRBTreeEntry))
return false;
final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o;
final K key = entry.getKey();
if (!inRange(key))
return false;
final OMVRBTreeEntry<K, V> node = m.getEntry(key, PartialSearchMode.NONE);
if (node != null && valEquals(node.getValue(), entry.getValue())) {
m.deleteEntry(node);
return true;
}
return false;
}
}
/**
* Iterators for SubMaps
*/
abstract class SubMapIterator<T> implements OLazyIterator<T> {
OMVRBTreeEntryPosition<K, V> lastReturned;
OMVRBTreeEntryPosition<K, V> next;
final K fenceKey;
int expectedModCount;
SubMapIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) {
expectedModCount = m.modCount;
lastReturned = null;
next = first;
fenceKey = fence == null ? null : fence.getKey();
}
public final boolean hasNext() {
if (next != null) {
final K k = next.getKey();
return k != fenceKey && !k.equals(fenceKey);
}
return false;
}
final OMVRBTreeEntryPosition<K, V> nextEntry() {
final OMVRBTreeEntryPosition<K, V> e;
if (next != null)
e = new OMVRBTreeEntryPosition<K, V>(next);
else
e = null;
if (e == null || e.entry == null)
throw new NoSuchElementException();
final K k = e.getKey();
if (k == fenceKey || k.equals(fenceKey))
throw new NoSuchElementException();
if (m.modCount != expectedModCount)
throw new ConcurrentModificationException();
next.assign(OMVRBTree.next(e));
lastReturned = e;
return e;
}
final OMVRBTreeEntryPosition<K, V> prevEntry() {
final OMVRBTreeEntryPosition<K, V> e;
if (next != null)
e = new OMVRBTreeEntryPosition<K, V>(next);
else
e = null;
if (e == null || e.entry == null)
throw new NoSuchElementException();
final K k = e.getKey();
if (k == fenceKey || k.equals(fenceKey))
throw new NoSuchElementException();
if (m.modCount != expectedModCount)
throw new ConcurrentModificationException();
next.assign(OMVRBTree.previous(e));
lastReturned = e;
return e;
}
final public T update(final T iValue) {
if (lastReturned == null)
throw new IllegalStateException();
if (m.modCount != expectedModCount)
throw new ConcurrentModificationException();
return (T) lastReturned.entry.setValue((V) iValue);
}
final void removeAscending() {
if (lastReturned == null)
throw new IllegalStateException();
if (m.modCount != expectedModCount)
throw new ConcurrentModificationException();
// deleted entries are replaced by their successors
if (lastReturned.entry.getLeft() != null && lastReturned.entry.getRight() != null)
next = lastReturned;
m.deleteEntry(lastReturned.entry);
lastReturned = null;
expectedModCount = m.modCount;
}
final void removeDescending() {
if (lastReturned == null)
throw new IllegalStateException();
if (m.modCount != expectedModCount)
throw new ConcurrentModificationException();
m.deleteEntry(lastReturned.entry);
lastReturned = null;
expectedModCount = m.modCount;
}
}
final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K, V>> {
SubMapEntryIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) {
super(first, fence);
}
public Map.Entry<K, V> next() {
final Map.Entry<K, V> e = OMVRBTree.exportEntry(next);
nextEntry();
return e;
}
public void remove() {
removeAscending();
}
}
final class SubMapKeyIterator extends SubMapIterator<K> {
SubMapKeyIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) {
super(first, fence);
}
public K next() {
return nextEntry().getKey();
}
public void remove() {
removeAscending();
}
}
final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K, V>> {
DescendingSubMapEntryIterator(final OMVRBTreeEntryPosition<K, V> last, final OMVRBTreeEntryPosition<K, V> fence) {
super(last, fence);
}
public Map.Entry<K, V> next() {
final Map.Entry<K, V> e = OMVRBTree.exportEntry(next);
prevEntry();
return e;
}
public void remove() {
removeDescending();
}
}
final class DescendingSubMapKeyIterator extends SubMapIterator<K> {
DescendingSubMapKeyIterator(final OMVRBTreeEntryPosition<K, V> last, final OMVRBTreeEntryPosition<K, V> fence) {
super(last, fence);
}
public K next() {
return prevEntry().getKey();
}
public void remove() {
removeDescending();
}
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
23 | final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K, V>> {
DescendingSubMapEntryIterator(final OMVRBTreeEntryPosition<K, V> last, final OMVRBTreeEntryPosition<K, V> fence) {
super(last, fence);
}
public Map.Entry<K, V> next() {
final Map.Entry<K, V> e = OMVRBTree.exportEntry(next);
prevEntry();
return e;
}
public void remove() {
removeDescending();
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
24 | final class DescendingSubMapKeyIterator extends SubMapIterator<K> {
DescendingSubMapKeyIterator(final OMVRBTreeEntryPosition<K, V> last, final OMVRBTreeEntryPosition<K, V> fence) {
super(last, fence);
}
public K next() {
return prevEntry().getKey();
}
public void remove() {
removeDescending();
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
25 | abstract class EntrySetView extends AbstractSet<Map.Entry<K, V>> {
private transient int size = -1, sizeModCount;
@Override
public int size() {
if (fromStart && toEnd)
return m.size();
if (size == -1 || sizeModCount != m.modCount) {
sizeModCount = m.modCount;
size = 0;
Iterator<?> i = iterator();
while (i.hasNext()) {
size++;
i.next();
}
}
return size;
}
@Override
public boolean isEmpty() {
OMVRBTreeEntryPosition<K, V> n = absLowest();
return n == null || tooHigh(n.getKey());
}
@Override
public boolean contains(final Object o) {
if (!(o instanceof OMVRBTreeEntry))
return false;
final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o;
final K key = entry.getKey();
if (!inRange(key))
return false;
V nodeValue = m.get(key);
return nodeValue != null && valEquals(nodeValue, entry.getValue());
}
@Override
public boolean remove(final Object o) {
if (!(o instanceof OMVRBTreeEntry))
return false;
final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o;
final K key = entry.getKey();
if (!inRange(key))
return false;
final OMVRBTreeEntry<K, V> node = m.getEntry(key, PartialSearchMode.NONE);
if (node != null && valEquals(node.getValue(), entry.getValue())) {
m.deleteEntry(node);
return true;
}
return false;
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
26 | final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K, V>> {
SubMapEntryIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) {
super(first, fence);
}
public Map.Entry<K, V> next() {
final Map.Entry<K, V> e = OMVRBTree.exportEntry(next);
nextEntry();
return e;
}
public void remove() {
removeAscending();
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
27 | abstract class SubMapIterator<T> implements OLazyIterator<T> {
OMVRBTreeEntryPosition<K, V> lastReturned;
OMVRBTreeEntryPosition<K, V> next;
final K fenceKey;
int expectedModCount;
SubMapIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) {
expectedModCount = m.modCount;
lastReturned = null;
next = first;
fenceKey = fence == null ? null : fence.getKey();
}
public final boolean hasNext() {
if (next != null) {
final K k = next.getKey();
return k != fenceKey && !k.equals(fenceKey);
}
return false;
}
final OMVRBTreeEntryPosition<K, V> nextEntry() {
final OMVRBTreeEntryPosition<K, V> e;
if (next != null)
e = new OMVRBTreeEntryPosition<K, V>(next);
else
e = null;
if (e == null || e.entry == null)
throw new NoSuchElementException();
final K k = e.getKey();
if (k == fenceKey || k.equals(fenceKey))
throw new NoSuchElementException();
if (m.modCount != expectedModCount)
throw new ConcurrentModificationException();
next.assign(OMVRBTree.next(e));
lastReturned = e;
return e;
}
final OMVRBTreeEntryPosition<K, V> prevEntry() {
final OMVRBTreeEntryPosition<K, V> e;
if (next != null)
e = new OMVRBTreeEntryPosition<K, V>(next);
else
e = null;
if (e == null || e.entry == null)
throw new NoSuchElementException();
final K k = e.getKey();
if (k == fenceKey || k.equals(fenceKey))
throw new NoSuchElementException();
if (m.modCount != expectedModCount)
throw new ConcurrentModificationException();
next.assign(OMVRBTree.previous(e));
lastReturned = e;
return e;
}
final public T update(final T iValue) {
if (lastReturned == null)
throw new IllegalStateException();
if (m.modCount != expectedModCount)
throw new ConcurrentModificationException();
return (T) lastReturned.entry.setValue((V) iValue);
}
final void removeAscending() {
if (lastReturned == null)
throw new IllegalStateException();
if (m.modCount != expectedModCount)
throw new ConcurrentModificationException();
// deleted entries are replaced by their successors
if (lastReturned.entry.getLeft() != null && lastReturned.entry.getRight() != null)
next = lastReturned;
m.deleteEntry(lastReturned.entry);
lastReturned = null;
expectedModCount = m.modCount;
}
final void removeDescending() {
if (lastReturned == null)
throw new IllegalStateException();
if (m.modCount != expectedModCount)
throw new ConcurrentModificationException();
m.deleteEntry(lastReturned.entry);
lastReturned = null;
expectedModCount = m.modCount;
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
28 | final class SubMapKeyIterator extends SubMapIterator<K> {
SubMapKeyIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) {
super(first, fence);
}
public K next() {
return nextEntry().getKey();
}
public void remove() {
removeAscending();
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
29 | public static enum PartialSearchMode {
/**
* Any partially matched key will be used as search result.
*/
NONE,
/**
* The biggest partially matched key will be used as search result.
*/
HIGHEST_BOUNDARY,
/**
* The smallest partially matched key will be used as search result.
*/
LOWEST_BOUNDARY
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
30 | final class ValueInverseIterator extends AbstractEntryIterator<K, V, V> {
ValueInverseIterator(final OMVRBTreeEntry<K, V> last) {
super(last);
// we have to set ourselves after current index to make iterator work
if (last != null) {
pageIndex = last.getTree().getPageIndex() + 1;
}
}
@Override
public boolean hasNext() {
return hasPrevious();
}
@Override
public V next() {
return prevValue();
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
31 | final class ValueIterator extends AbstractEntryIterator<K, V, V> {
ValueIterator(final OMVRBTreeEntry<K, V> first) {
super(first);
}
@Override
public V next() {
return nextValue();
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
32 | public class Values extends AbstractCollection<V> {
@Override
public Iterator<V> iterator() {
return new ValueIterator(getFirstEntry());
}
public Iterator<V> inverseIterator() {
return new ValueInverseIterator(getLastEntry());
}
@Override
public int size() {
return OMVRBTree.this.size();
}
@Override
public boolean contains(final Object o) {
return OMVRBTree.this.containsValue(o);
}
@Override
public boolean remove(final Object o) {
for (OMVRBTreeEntry<K, V> e = getFirstEntry(); e != null; e = next(e)) {
if (valEquals(e.getValue(), o)) {
deleteEntry(e);
return true;
}
}
return false;
}
@Override
public void clear() {
OMVRBTree.this.clear();
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
33 | @Test
public class OMVRBTreeCompositeTest {
protected OMVRBTree<OCompositeKey, Double> tree;
@BeforeMethod
public void beforeMethod() throws Exception {
tree = new OMVRBTreeMemory<OCompositeKey, Double>(4, 0.5f, 2);
for (double i = 1; i < 4; i++) {
for (double j = 1; j < 10; j++) {
final OCompositeKey compositeKey = new OCompositeKey();
compositeKey.addKey(i);
compositeKey.addKey(j);
tree.put(compositeKey, i * 4 + j);
}
}
}
@Test
public void testGetEntrySameKeys() {
OMVRBTreeEntry<OCompositeKey, Double> result = tree.getEntry(compositeKey(1.0, 2.0), OMVRBTree.PartialSearchMode.NONE);
assertEquals(result.getKey(), compositeKey(1.0, 2.0));
result = tree.getEntry(compositeKey(1.0, 2.0), OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY);
assertEquals(result.getKey(), compositeKey(1.0, 2.0));
result = tree.getEntry(compositeKey(1.0, 2.0), OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY);
assertEquals(result.getKey(), compositeKey(1.0, 2.0));
}
@Test
public void testGetEntryPartialKeys() {
OMVRBTreeEntry<OCompositeKey, Double> result = tree.getEntry(compositeKey(2.0), OMVRBTree.PartialSearchMode.NONE);
assertEquals(result.getKey().getKeys().get(0), 2.0);
result = tree.getEntry(compositeKey(2.0), OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY);
assertEquals(result.getKey(), compositeKey(2.0, 1.0));
result = tree.getEntry(compositeKey(2.0), OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY);
assertEquals(result.getKey(), compositeKey(2.0, 9.0));
}
@Test
public void testSubMapInclusiveDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), true, compositeKey(3.0), true)
.descendingMap();
assertEquals(navigableMap.size(), 18);
for (double i = 2; i <= 3; i++) {
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
}
@Test
public void testSubMapFromInclusiveDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), true, compositeKey(3.0), false)
.descendingMap();
assertEquals(navigableMap.size(), 9);
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(2.0, j)));
}
}
@Test
public void testSubMapToInclusiveDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), false, compositeKey(3.0), true)
.descendingMap();
assertEquals(navigableMap.size(), 9);
for (double i = 1; i <= 9; i++) {
assertTrue(navigableMap.containsKey(compositeKey(3.0, i)));
}
}
@Test
public void testSubMapNonInclusiveDescending() {
ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), false, compositeKey(3.0), false)
.descendingMap();
assertEquals(navigableMap.size(), 0);
assertTrue(navigableMap.isEmpty());
navigableMap = tree.subMap(compositeKey(1.0), false, compositeKey(3.0), false);
assertEquals(navigableMap.size(), 9);
for (double i = 1; i <= 9; i++) {
assertTrue(navigableMap.containsKey(compositeKey(2.0, i)));
}
}
@Test
public void testSubMapInclusive() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), true, compositeKey(3.0), true);
assertEquals(navigableMap.size(), 18);
for (double i = 2; i <= 3; i++) {
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
}
@Test
public void testSubMapFromInclusive() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), true, compositeKey(3.0), false);
assertEquals(navigableMap.size(), 9);
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(2.0, j)));
}
}
@Test
public void testSubMapToInclusive() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), false, compositeKey(3.0), true);
assertEquals(navigableMap.size(), 9);
for (double i = 1; i <= 9; i++) {
assertTrue(navigableMap.containsKey(compositeKey(3.0, i)));
}
}
@Test
public void testSubMapNonInclusive() {
ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), false, compositeKey(3.0), false);
assertEquals(navigableMap.size(), 0);
assertTrue(navigableMap.isEmpty());
navigableMap = tree.subMap(compositeKey(1.0), false, compositeKey(3.0), false);
assertEquals(navigableMap.size(), 9);
for (double i = 1; i <= 9; i++) {
assertTrue(navigableMap.containsKey(compositeKey(2.0, i)));
}
}
@Test
public void testSubMapInclusivePartialKey() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), true, compositeKey(3.0), true);
assertEquals(navigableMap.size(), 15);
for (double i = 2; i <= 3; i++) {
for (double j = 1; j <= 9; j++) {
if (i == 2 && j < 4)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
}
@Test
public void testSubMapFromInclusivePartialKey() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), true, compositeKey(3.0), false);
assertEquals(navigableMap.size(), 6);
for (double j = 4; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(2.0, j)));
}
}
@Test
public void testSubMapToInclusivePartialKey() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), false, compositeKey(3.0), true);
assertEquals(navigableMap.size(), 14);
for (double i = 2; i <= 3; i++) {
for (double j = 1; j <= 9; j++) {
if (i == 2 && j <= 4)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
}
@Test
public void testSubMapNonInclusivePartial() {
ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), false, compositeKey(3.0), false);
assertEquals(navigableMap.size(), 5);
for (double i = 5; i <= 9; i++) {
assertTrue(navigableMap.containsKey(compositeKey(2.0, i)));
}
}
@Test
public void testSubMapInclusivePartialKeyDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), true, compositeKey(3.0), true)
.descendingMap();
assertEquals(navigableMap.size(), 15);
for (double i = 2; i <= 3; i++) {
for (double j = 1; j <= 9; j++) {
if (i == 2 && j < 4)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
}
@Test
public void testSubMapFromInclusivePartialKeyDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), true, compositeKey(3.0), false)
.descendingMap();
assertEquals(navigableMap.size(), 6);
for (double j = 4; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(2.0, j)));
}
}
@Test
public void testSubMapToInclusivePartialKeyDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), false, compositeKey(3.0), true)
.descendingMap();
assertEquals(navigableMap.size(), 14);
for (double i = 2; i <= 3; i++) {
for (double j = 1; j <= 9; j++) {
if (i == 2 && j <= 4)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
}
@Test
public void testSubMapNonInclusivePartialDescending() {
ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), false, compositeKey(3.0), false)
.descendingMap();
assertEquals(navigableMap.size(), 5);
for (double i = 5; i <= 9; i++) {
assertTrue(navigableMap.containsKey(compositeKey(2.0, i)));
}
}
@Test
public void testTailMapInclusivePartial() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0), true);
assertEquals(navigableMap.size(), 18);
for (double i = 2; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testTailMapNonInclusivePartial() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0), false);
assertEquals(navigableMap.size(), 9);
for (double i = 1; i <= 9; i++) {
assertTrue(navigableMap.containsKey(compositeKey(3.0, i)));
}
}
@Test
public void testTailMapInclusivePartialDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0), true).descendingMap();
assertEquals(navigableMap.size(), 18);
for (double i = 2; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testTailMapNonInclusivePartialDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0), false).descendingMap();
assertEquals(navigableMap.size(), 9);
for (double i = 1; i <= 9; i++) {
assertTrue(navigableMap.containsKey(compositeKey(3.0, i)));
}
}
@Test
public void testTailMapInclusive() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0, 3.0), true);
assertEquals(navigableMap.size(), 16);
for (double i = 2; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
if (i == 2 && j < 3)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testTailMapNonInclusive() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0, 3.0), false);
assertEquals(navigableMap.size(), 15);
for (double i = 2; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
if (i == 2 && j <= 3)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testTailMapInclusiveDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0, 3.0), true).descendingMap();
assertEquals(navigableMap.size(), 16);
for (double i = 2; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
if (i == 2 && j < 3)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testTailMapNonInclusiveDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0, 3.0), false).descendingMap();
assertEquals(navigableMap.size(), 15);
for (double i = 2; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
if (i == 2 && j <= 3)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testHeadMapInclusivePartial() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0), true);
assertEquals(navigableMap.size(), 27);
for (double i = 1; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testHeadMapNonInclusivePartial() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0), false);
assertEquals(navigableMap.size(), 18);
for (double i = 1; i < 3; i++)
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testHeadMapInclusivePartialDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0), true).descendingMap();
assertEquals(navigableMap.size(), 27);
for (double i = 1; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testHeadMapNonInclusivePartialDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0), false).descendingMap();
assertEquals(navigableMap.size(), 18);
for (double i = 1; i < 3; i++)
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testHeadMapInclusive() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0, 2.0), true);
assertEquals(navigableMap.size(), 20);
for (double i = 1; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
if (i == 3 && j > 2)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testHeadMapNonInclusive() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0, 2.0), false);
assertEquals(navigableMap.size(), 19);
for (double i = 1; i < 3; i++)
for (double j = 1; j <= 9; j++) {
if (i == 3 && j >= 2)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testHeadMapInclusiveDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0, 2.0), true).descendingMap();
assertEquals(navigableMap.size(), 20);
for (double i = 1; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
if (i == 3 && j > 2)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testHeadMapNonInclusiveDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0, 2.0), false).descendingMap();
assertEquals(navigableMap.size(), 19);
for (double i = 1; i < 3; i++)
for (double j = 1; j <= 9; j++) {
if (i == 3 && j >= 2)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testGetCeilingEntryKeyExistPartial() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getCeilingEntry(compositeKey(3.0), OMVRBTree.PartialSearchMode.NONE);
assertEquals(entry.getKey().getKeys().get(0), 3.0);
entry = tree.getCeilingEntry(compositeKey(3.0), OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY);
assertEquals(entry.getKey(), compositeKey(3.0, 9.0));
entry = tree.getCeilingEntry(compositeKey(3.0), OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY);
assertEquals(entry.getKey(), compositeKey(3.0, 1.0));
}
@Test
public void testGetCeilingEntryKeyNotExistPartial() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getCeilingEntry(compositeKey(1.3), OMVRBTree.PartialSearchMode.NONE);
assertEquals(entry.getKey().getKeys().get(0), 2.0);
entry = tree.getCeilingEntry(compositeKey(1.3), OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY);
assertEquals(entry.getKey(), compositeKey(2.0, 9.0));
entry = tree.getCeilingEntry(compositeKey(1.3), OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY);
assertEquals(entry.getKey(), compositeKey(2.0, 1.0));
}
@Test
public void testGetFloorEntryKeyExistPartial() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getFloorEntry(compositeKey(2.0), OMVRBTree.PartialSearchMode.NONE);
assertEquals(entry.getKey().getKeys().get(0), 2.0);
entry = tree.getFloorEntry(compositeKey(2.0), OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY);
assertEquals(entry.getKey(), compositeKey(2.0, 9.0));
entry = tree.getFloorEntry(compositeKey(2.0), OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY);
assertEquals(entry.getKey(), compositeKey(2.0, 1.0));
}
@Test
public void testGetFloorEntryKeyNotExistPartial() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getFloorEntry(compositeKey(1.3), OMVRBTree.PartialSearchMode.NONE);
assertEquals(entry.getKey().getKeys().get(0), 1.0);
entry = tree.getFloorEntry(compositeKey(1.3), OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY);
assertEquals(entry.getKey(), compositeKey(1.0, 9.0));
entry = tree.getFloorEntry(compositeKey(1.3), OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY);
assertEquals(entry.getKey(), compositeKey(1.0, 1.0));
}
@Test
public void testHigherEntryKeyExistPartial() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getHigherEntry(compositeKey(2.0));
assertEquals(entry.getKey(), compositeKey(3.0, 1.0));
}
@Test
public void testHigherEntryKeyNotExist() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getHigherEntry(compositeKey(1.3));
assertEquals(entry.getKey(), compositeKey(2.0, 1.0));
}
@Test
public void testHigherEntryNullResult() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getHigherEntry(compositeKey(12.0));
assertNull(entry);
}
@Test
public void testLowerEntryNullResult() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getLowerEntry(compositeKey(0.0));
assertNull(entry);
}
@Test
public void testLowerEntryKeyExist() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getLowerEntry(compositeKey(2.0));
assertEquals(entry.getKey(), compositeKey(1.0, 9.0));
}
@Test
public void testLowerEntryKeyNotExist() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getLowerEntry(compositeKey(2.5));
assertEquals(entry.getKey(), compositeKey(2.0, 9.0));
}
private OCompositeKey compositeKey(Comparable<?>... params) {
return new OCompositeKey(Arrays.asList(params));
}
} | false | core_src_test_java_com_orientechnologies_common_collection_OMVRBTreeCompositeTest.java |
34 | @SuppressWarnings("unchecked")
public abstract class OMVRBTreeEntry<K, V> implements Map.Entry<K, V>, Comparable<OMVRBTreeEntry<K, V>> {
protected OMVRBTree<K, V> tree;
private int pageSplitItems;
public static final int BINARY_SEARCH_THRESHOLD = 10;
/**
* Constructor called on unmarshalling.
*
*/
protected OMVRBTreeEntry(final OMVRBTree<K, V> iTree) {
tree = iTree;
}
public abstract void setLeft(OMVRBTreeEntry<K, V> left);
public abstract OMVRBTreeEntry<K, V> getLeft();
public abstract void setRight(OMVRBTreeEntry<K, V> right);
public abstract OMVRBTreeEntry<K, V> getRight();
public abstract OMVRBTreeEntry<K, V> setParent(OMVRBTreeEntry<K, V> parent);
public abstract OMVRBTreeEntry<K, V> getParent();
protected abstract OMVRBTreeEntry<K, V> getLeftInMemory();
protected abstract OMVRBTreeEntry<K, V> getParentInMemory();
protected abstract OMVRBTreeEntry<K, V> getRightInMemory();
protected abstract OMVRBTreeEntry<K, V> getNextInMemory();
/**
* Returns the first Entry only by traversing the memory, or null if no such.
*/
public OMVRBTreeEntry<K, V> getFirstInMemory() {
OMVRBTreeEntry<K, V> node = this;
OMVRBTreeEntry<K, V> prev = this;
while (node != null) {
prev = node;
node = node.getPreviousInMemory();
}
return prev;
}
/**
* Returns the previous of the current Entry only by traversing the memory, or null if no such.
*/
public OMVRBTreeEntry<K, V> getPreviousInMemory() {
OMVRBTreeEntry<K, V> t = this;
OMVRBTreeEntry<K, V> p = null;
if (t.getLeftInMemory() != null) {
p = t.getLeftInMemory();
while (p.getRightInMemory() != null)
p = p.getRightInMemory();
} else {
p = t.getParentInMemory();
while (p != null && t == p.getLeftInMemory()) {
t = p;
p = p.getParentInMemory();
}
}
return p;
}
protected OMVRBTree<K, V> getTree() {
return tree;
}
public int getDepth() {
int level = 0;
OMVRBTreeEntry<K, V> entry = this;
while (entry.getParent() != null) {
level++;
entry = entry.getParent();
}
return level;
}
/**
* Returns the key.
*
* @return the key
*/
public K getKey() {
return getKey(tree.pageIndex);
}
public K getKey(final int iIndex) {
if (iIndex >= getSize())
throw new IndexOutOfBoundsException("Requested index " + iIndex + " when the range is 0-" + getSize());
tree.pageIndex = iIndex;
return getKeyAt(iIndex);
}
protected abstract K getKeyAt(final int iIndex);
/**
* Returns the value associated with the key.
*
* @return the value associated with the key
*/
public V getValue() {
if (tree.pageIndex == -1)
return getValueAt(0);
return getValueAt(tree.pageIndex);
}
public V getValue(final int iIndex) {
tree.pageIndex = iIndex;
return getValueAt(iIndex);
}
protected abstract V getValueAt(int iIndex);
public int getFreeSpace() {
return getPageSize() - getSize();
}
/**
* Execute a binary search between the keys of the node. The keys are always kept ordered. It update the pageIndex attribute with
* the most closer key found (useful for the next inserting).
*
* @param iKey
* Key to find
* @return The value found if any, otherwise null
*/
protected V search(final K iKey) {
tree.pageItemFound = false;
int size = getSize();
if (size == 0)
return null;
// CHECK THE LOWER LIMIT
if (tree.comparator != null)
tree.pageItemComparator = tree.comparator.compare(iKey, getKeyAt(0));
else
tree.pageItemComparator = ((Comparable<? super K>) iKey).compareTo(getKeyAt(0));
if (tree.pageItemComparator == 0) {
// FOUND: SET THE INDEX AND RETURN THE NODE
tree.pageItemFound = true;
tree.pageIndex = 0;
return getValueAt(tree.pageIndex);
} else if (tree.pageItemComparator < 0) {
// KEY OUT OF FIRST ITEM: AVOID SEARCH AND RETURN THE FIRST POSITION
tree.pageIndex = 0;
return null;
} else {
// CHECK THE UPPER LIMIT
if (tree.comparator != null)
tree.pageItemComparator = tree.comparator.compare((K) iKey, getKeyAt(size - 1));
else
tree.pageItemComparator = ((Comparable<? super K>) iKey).compareTo(getKeyAt(size - 1));
if (tree.pageItemComparator > 0) {
// KEY OUT OF LAST ITEM: AVOID SEARCH AND RETURN THE LAST POSITION
tree.pageIndex = size;
return null;
}
}
if (size < BINARY_SEARCH_THRESHOLD)
return linearSearch(iKey);
else
return binarySearch(iKey);
}
/**
* Linear search inside the node
*
* @param iKey
* Key to search
* @return Value if found, otherwise null and the tree.pageIndex updated with the closest-after-first position valid for further
* inserts.
*/
private V linearSearch(final K iKey) {
V value = null;
int i = 0;
tree.pageItemComparator = -1;
for (int s = getSize(); i < s; ++i) {
if (tree.comparator != null)
tree.pageItemComparator = tree.comparator.compare(getKeyAt(i), iKey);
else
tree.pageItemComparator = ((Comparable<? super K>) getKeyAt(i)).compareTo(iKey);
if (tree.pageItemComparator == 0) {
// FOUND: SET THE INDEX AND RETURN THE NODE
tree.pageItemFound = true;
value = getValueAt(i);
break;
} else if (tree.pageItemComparator > 0)
break;
}
tree.pageIndex = i;
return value;
}
/**
* Binary search inside the node
*
* @param iKey
* Key to search
* @return Value if found, otherwise null and the tree.pageIndex updated with the closest-after-first position valid for further
* inserts.
*/
private V binarySearch(final K iKey) {
int low = 0;
int high = getSize() - 1;
int mid = 0;
while (low <= high) {
mid = (low + high) >>> 1;
Object midVal = getKeyAt(mid);
if (tree.comparator != null)
tree.pageItemComparator = tree.comparator.compare((K) midVal, iKey);
else
tree.pageItemComparator = ((Comparable<? super K>) midVal).compareTo(iKey);
if (tree.pageItemComparator == 0) {
// FOUND: SET THE INDEX AND RETURN THE NODE
tree.pageItemFound = true;
tree.pageIndex = mid;
return getValueAt(tree.pageIndex);
}
if (low == high)
break;
if (tree.pageItemComparator < 0)
low = mid + 1;
else
high = mid;
}
tree.pageIndex = mid;
return null;
}
protected abstract void insert(final int iPosition, final K key, final V value);
protected abstract void remove();
protected abstract void setColor(boolean iColor);
public abstract boolean getColor();
public abstract int getSize();
public K getLastKey() {
return getKey(getSize() - 1);
}
public K getFirstKey() {
return getKey(0);
}
protected abstract void copyFrom(final OMVRBTreeEntry<K, V> iSource);
public int getPageSplitItems() {
return pageSplitItems;
}
protected void init() {
pageSplitItems = (int) (getPageSize() * tree.pageLoadFactor);
}
public abstract int getPageSize();
/**
* Compares two nodes by their first keys.
*/
public int compareTo(final OMVRBTreeEntry<K, V> o) {
if (o == null)
return 1;
if (o == this)
return 0;
if (getSize() == 0)
return -1;
if (o.getSize() == 0)
return 1;
if (tree.comparator != null)
return tree.comparator.compare(getFirstKey(), o.getFirstKey());
return ((Comparable<K>) getFirstKey()).compareTo(o.getFirstKey());
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
int idx = tree.pageIndex;
if (idx > -1 && idx < getSize())
return getKeyAt(idx) + "=" + getValueAt(idx);
return null;
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTreeEntry.java |
35 | @SuppressWarnings("unchecked")
public class OMVRBTreeEntryMemory<K, V> extends OMVRBTreeEntry<K, V> {
protected int size = 1;
protected int pageSize;
protected K[] keys;
protected V[] values;
protected OMVRBTreeEntryMemory<K, V> left = null;
protected OMVRBTreeEntryMemory<K, V> right = null;
protected OMVRBTreeEntryMemory<K, V> parent;
protected boolean color = OMVRBTree.RED;
/**
* Constructor called on unmarshalling.
*
*/
protected OMVRBTreeEntryMemory(final OMVRBTree<K, V> iTree) {
super(iTree);
}
/**
* Make a new cell with given key, value, and parent, and with <tt>null</tt> child links, and BLACK color.
*/
protected OMVRBTreeEntryMemory(final OMVRBTree<K, V> iTree, final K iKey, final V iValue, final OMVRBTreeEntryMemory<K, V> iParent) {
super(iTree);
setParent(iParent);
pageSize = tree.getDefaultPageSize();
keys = (K[]) new Object[pageSize];
keys[0] = iKey;
values = (V[]) new Object[pageSize];
values[0] = iValue;
init();
}
/**
* Copy values from the parent node.
*
* @param iParent
* @param iPosition
*/
protected OMVRBTreeEntryMemory(final OMVRBTreeEntryMemory<K, V> iParent, final int iPosition) {
super(iParent.getTree());
pageSize = tree.getDefaultPageSize();
keys = (K[]) new Object[pageSize];
values = (V[]) new Object[pageSize];
size = iParent.size - iPosition;
System.arraycopy(iParent.keys, iPosition, keys, 0, size);
System.arraycopy(iParent.values, iPosition, values, 0, size);
Arrays.fill(iParent.keys, iPosition, iParent.size, null);
Arrays.fill(iParent.values, iPosition, iParent.size, null);
iParent.size = iPosition;
setParent(iParent);
init();
}
@Override
protected void setColor(final boolean iColor) {
this.color = iColor;
}
@Override
public boolean getColor() {
return color;
}
@Override
public void setLeft(final OMVRBTreeEntry<K, V> iLeft) {
left = (OMVRBTreeEntryMemory<K, V>) iLeft;
if (iLeft != null && iLeft.getParent() != this)
iLeft.setParent(this);
}
@Override
public OMVRBTreeEntry<K, V> getLeft() {
return left;
}
@Override
public void setRight(final OMVRBTreeEntry<K, V> iRight) {
right = (OMVRBTreeEntryMemory<K, V>) iRight;
if (iRight != null && iRight.getParent() != this)
iRight.setParent(this);
}
@Override
public OMVRBTreeEntry<K, V> getRight() {
return right;
}
@Override
public OMVRBTreeEntry<K, V> setParent(final OMVRBTreeEntry<K, V> iParent) {
parent = (OMVRBTreeEntryMemory<K, V>) iParent;
return iParent;
}
@Override
public OMVRBTreeEntry<K, V> getParent() {
return parent;
}
/**
* Returns the successor of the current Entry only by traversing the memory, or null if no such.
*/
@Override
public OMVRBTreeEntryMemory<K, V> getNextInMemory() {
OMVRBTreeEntryMemory<K, V> t = this;
OMVRBTreeEntryMemory<K, V> p = null;
if (t.right != null) {
p = t.right;
while (p.left != null)
p = p.left;
} else {
p = t.parent;
while (p != null && t == p.right) {
t = p;
p = p.parent;
}
}
return p;
}
public int getSize() {
return size;
}
public int getPageSize() {
return pageSize;
}
@Override
protected OMVRBTreeEntry<K, V> getLeftInMemory() {
return left;
}
@Override
protected OMVRBTreeEntry<K, V> getParentInMemory() {
return parent;
}
@Override
protected OMVRBTreeEntry<K, V> getRightInMemory() {
return right;
}
protected K getKeyAt(final int iIndex) {
return keys[iIndex];
}
protected V getValueAt(int iIndex) {
return values[iIndex];
}
/**
* Replaces the value currently associated with the key with the given value.
*
* @return the value associated with the key before this method was called
*/
public V setValue(final V value) {
V oldValue = this.getValue();
this.values[tree.pageIndex] = value;
return oldValue;
}
protected void insert(final int iPosition, final K key, final V value) {
if (iPosition < size) {
// MOVE RIGHT TO MAKE ROOM FOR THE ITEM
System.arraycopy(keys, iPosition, keys, iPosition + 1, size - iPosition);
System.arraycopy(values, iPosition, values, iPosition + 1, size - iPosition);
}
keys[iPosition] = key;
values[iPosition] = value;
size++;
}
protected void remove() {
if (tree.pageIndex == size - 1) {
// LAST ONE: JUST REMOVE IT
} else if (tree.pageIndex > -1) {
// SHIFT LEFT THE VALUES
System.arraycopy(keys, tree.pageIndex + 1, keys, tree.pageIndex, size - tree.pageIndex - 1);
System.arraycopy(values, tree.pageIndex + 1, values, tree.pageIndex, size - tree.pageIndex - 1);
}
// FREE RESOURCES
keys[size - 1] = null;
values[size - 1] = null;
size--;
tree.pageIndex = 0;
}
protected void copyFrom(final OMVRBTreeEntry<K, V> iSource) {
OMVRBTreeEntryMemory<K, V> source = (OMVRBTreeEntryMemory<K, V>) iSource;
keys = (K[]) new Object[source.keys.length];
for (int i = 0; i < source.keys.length; ++i)
keys[i] = source.keys[i];
values = (V[]) new Object[source.values.length];
for (int i = 0; i < source.values.length; ++i)
values[i] = source.values[i];
size = source.size;
}
@Override
public String toString() {
if (keys == null)
return "?";
final StringBuilder buffer = new StringBuilder();
final Object k = tree.pageIndex >= size ? '?' : getKey();
buffer.append(k);
buffer.append(" (size=");
buffer.append(size);
if (size > 0) {
buffer.append(" [");
buffer.append(keys[0] != null ? keys[0] : "{lazy}");
buffer.append('-');
buffer.append(keys[size - 1] != null ? keys[size - 1] : "{lazy}");
buffer.append(']');
}
buffer.append(')');
return buffer.toString();
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTreeEntryMemory.java |
36 | public class OMVRBTreeEntryPosition<K, V> {
public OMVRBTreeEntry<K, V> entry;
public int position;
public OMVRBTreeEntryPosition(final OMVRBTreeEntryPosition<K, V> entryPosition) {
this.entry = entryPosition.entry;
this.position = entryPosition.position;
}
public OMVRBTreeEntryPosition(final OMVRBTreeEntry<K, V> entry) {
assign(entry);
}
public OMVRBTreeEntryPosition(final OMVRBTreeEntry<K, V> entry, final int iPosition) {
assign(entry, iPosition);
}
public void assign(final OMVRBTreeEntry<K, V> entry, final int iPosition) {
this.entry = entry;
this.position = iPosition;
}
public void assign(final OMVRBTreeEntry<K, V> entry) {
this.entry = entry;
this.position = entry != null ? entry.getTree().getPageIndex() : -1;
}
public K getKey() {
return entry != null ? entry.getKey(position) : null;
}
public V getValue() {
return entry != null ? entry.getValue(position) : null;
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTreeEntryPosition.java |
37 | @SuppressWarnings("serial")
public class OMVRBTreeMemory<K, V> extends OMVRBTree<K, V> {
/**
* The number of entries in the tree
*/
protected int size = 0;
protected int defaultPageSize = 63;
/**
* Memory based MVRB-Tree implementation. Constructs a new, empty tree map, using the natural ordering of its keys. All keys
* inserted into the map must implement the {@link Comparable} interface. Furthermore, all such keys must be <i>mutually
* comparable</i>: <tt>k1.compareTo(k2)</tt> must not throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and <tt>k2</tt>
* in the map. If the user attempts to put a key into the map that violates this constraint (for example, the user attempts to put
* a string key into a map whose keys are integers), the <tt>put(Object key, Object value)</tt> call will throw a
* <tt>ClassCastException</tt>.
*/
public OMVRBTreeMemory() {
runtimeCheckEnabled = false;
}
public OMVRBTreeMemory(final int iPageSize, final float iLoadFactor) {
this(iPageSize, iLoadFactor, 1);
}
public OMVRBTreeMemory(final int iPageSize, final float iLoadFactor, final int keySize) {
super(keySize);
defaultPageSize = iPageSize;
pageLoadFactor = iLoadFactor;
}
/**
* Constructs a new, empty tree map, ordered according to the given comparator. All keys inserted into the map must be <i>mutually
* comparable</i> by the given comparator: <tt>comparator.compare(k1,
* k2)</tt> must not throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and <tt>k2</tt> in the map. If the user attempts
* to put a key into the map that violates this constraint, the <tt>put(Object
* key, Object value)</tt> call will throw a <tt>ClassCastException</tt>.
*
* @param comparator
* the comparator that will be used to order this map. If <tt>null</tt>, the {@linkplain Comparable natural ordering} of
* the keys will be used.
*/
public OMVRBTreeMemory(final Comparator<? super K> comparator) {
super(comparator);
}
/**
* Constructs a new tree map containing the same mappings as the given map, ordered according to the <i>natural ordering</i> of
* its keys. All keys inserted into the new map must implement the {@link Comparable} interface. Furthermore, all such keys must
* be <i>mutually comparable</i>: <tt>k1.compareTo(k2)</tt> must not throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt>
* and <tt>k2</tt> in the map. This method runs in n*log(n) time.
*
* @param m
* the map whose mappings are to be placed in this map
* @throws ClassCastException
* if the keys in m are not {@link Comparable}, or are not mutually comparable
* @throws NullPointerException
* if the specified map is null
*/
public OMVRBTreeMemory(final Map<? extends K, ? extends V> m) {
super(m);
}
/**
* Constructs a new tree map containing the same mappings and using the same ordering as the specified sorted map. This method
* runs in linear time.
*
* @param m
* the sorted map whose mappings are to be placed in this map, and whose comparator is to be used to sort this map
* @throws NullPointerException
* if the specified map is null
*/
public OMVRBTreeMemory(final SortedMap<K, ? extends V> m) {
super(m);
}
@Override
public int getTreeSize() {
return size;
}
protected void setSize(int pSize) {
size = pSize;
}
public int getDefaultPageSize() {
return defaultPageSize;
}
@Override
protected OMVRBTreeEntry<K, V> createEntry(final K key, final V value) {
return new OMVRBTreeEntryMemory<K, V>(this, key, value, null);
}
@Override
protected OMVRBTreeEntry<K, V> createEntry(final OMVRBTreeEntry<K, V> parent) {
return new OMVRBTreeEntryMemory<K, V>((OMVRBTreeEntryMemory<K, V>) parent, parent.getPageSplitItems());
}
} | false | commons_src_main_java_com_orientechnologies_common_collection_OMVRBTreeMemory.java |
End of preview. Expand
in Dataset Viewer.
- Downloads last month
- 31