[jboss-svn-commits] JBL Code SVN: r6774 - in labs/jbossrules/trunk/drools-core/src: main/java/org/drools/common main/java/org/drools/util test/java/org/drools/util
jboss-svn-commits at lists.jboss.org
jboss-svn-commits at lists.jboss.org
Thu Oct 12 20:12:25 EDT 2006
Author: mark.proctor at jboss.com
Date: 2006-10-12 20:12:16 -0400 (Thu, 12 Oct 2006)
New Revision: 6774
Added:
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/BinaryHeapQueue.java
Removed:
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/ActivationQueue.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/AbstractHashedMap.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/BaseMultiLinkedListNode.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/BinaryHeapFifoQueue.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/EmptyMapIterator.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/FastCollection.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/FastComparator.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/FastIterator.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/FastMap.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/IdentityMap.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/MapIterator.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/MultiLinkedList.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/MultiLinkedListNode.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/MultiLinkedListNodeWrapper.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/PriorityQueue.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/TupleEntry.java
Modified:
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/AgendaGroupImpl.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/AgendaItem.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/EqualityAssertMapComparator.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/IdentityAssertMapComparator.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/RuleFlowNode.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/TruthMaintenanceSystem.java
labs/jbossrules/trunk/drools-core/src/test/java/org/drools/util/BinaryHeapPriorityQueueTest.java
Log:
JBRULES-498 Optimised HashMap implementations
-Cleanup of unused classes.
Modified: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java 2006-10-12 23:46:18 UTC (rev 6773)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -49,7 +49,6 @@
import org.drools.spi.FactHandleFactory;
import org.drools.spi.GlobalResolver;
import org.drools.spi.PropagationContext;
-import org.drools.util.FastMap;
import org.drools.util.ObjectHashMap;
import org.drools.util.PrimitiveLongMap;
import org.drools.util.concurrent.locks.Lock;
@@ -146,9 +145,9 @@
this.assertMap = new ObjectHashMap();
if ( RuleBaseConfiguration.WM_BEHAVIOR_IDENTITY.equals( conf.getProperty( RuleBaseConfiguration.PROPERTY_ASSERT_BEHAVIOR ) ) ) {
- this.assertMap.setComparator( EqualityKeyComparator.getInstance() );
+ this.assertMap.setComparator( new IdentityAssertMapComparator( this.handleFactory.getFactHandleType() ) );
} else {
- this.assertMap.setComparator( EqualityKeyComparator.getInstance() );
+ this.assertMap.setComparator( new EqualityAssertMapComparator( this.handleFactory.getFactHandleType() ) );
}
// Only takes effect if are using idententity behaviour for assert
Deleted: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/ActivationQueue.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/ActivationQueue.java 2006-10-12 23:46:18 UTC (rev 6773)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/ActivationQueue.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -1,160 +0,0 @@
-package org.drools.common;
-
-/*
- * Copyright 2005 JBoss Inc
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.drools.spi.Activation;
-import org.drools.util.LinkedList;
-import org.drools.util.LinkedListNode;
-
-/**
- * A LIFO <code>Activation</code> queue based on a <code>LinkedList</code>. Each salience rule value
- * is assigned an <code>ActivationQueue</code>, the salience number is used to prioritise the
- * <code>ActivationQueue</code> within the <code>PriorityQueue<code>. Each <code>Activation</code> in the queue
- * must implement the <code>LinkedListNode</code> interface. Each added <code>Activation</code>
- * is placed at the end of the queue; however <code>Activations</code> can be removed from the end or
- * from any point in queue.
- * <p>
- * <code>ActivationQueue</code> implements <code>Comparable</code>, based on the salience value, this
- * allows the queue to be correctly prioritised by salience value on the <code>PriorityQueue</code>.
- * <p>
- * When an <code>ActivationQueue</code> is placed onto a <code>PriorityQueue</code> it is considered active,
- * when it is removed it is inactivate. This ensures that an active <code>ActivationQueue</code> placed
- * onto a <code>PriorityQueue</code> cannot be re-added.
- *
- * @see LinkedList
- * @see PriorityQueue
- *
- * @author <a href="mailto:mark.proctor at jboss.com">Mark Proctor</a>
- * @author <a href="mailto:bob at werken.com">Bob McWhirter</a>
- */
-public class ActivationQueue
- implements
- Comparable {
- private LinkedList list;
-
- private final int salience;
-
- private boolean active;
-
- /**
- * Constructs a new <code>ActivationQueue</code> for a given saliene value using a
- * <code>LinkedList</code> to maintain the queue of <code>Activation</code>s.
- *
- * @param salience
- * The salience queue that the queue is for.
- */
- public ActivationQueue(final int salience) {
- this.salience = salience;
- this.list = new LinkedList();
- }
-
- /**
- * Returns the salience.
- * @return
- * The salience queue that the queue is for.
- */
- public int getSalience() {
- return this.salience;
- }
-
- /**
- * Has the queue been placed onto a <code>PriorityQueue</code>, if so this returns true until it
- * is removed.
- * @return
- * boolean
- */
- public boolean isActive() {
- return this.active;
- }
-
- /**
- * Specifies whether the queue has been placed onto a <code>PriorityQueue</code>. If it has
- * it is set to true, else it is set to false.
-
- * @param active
- * boolena value that sets the activate state.
- */
- public void setActivated(final boolean active) {
- this.active = active;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Comparable#compareTo(T)
- */
- public int compareTo(final Object object) {
- final ActivationQueue other = (ActivationQueue) object;
- return this.salience - other.salience;
- }
-
- /**
- * Add an <code>Activation</code> to the end of the queue
- * @param activation
- * the <code>Activation</code> to be placed onto the queue
- */
- public void add(final Activation activation) {
- this.list.add( (LinkedListNode) activation );
- }
-
- /**
- * Remove the <code>Activaton</code> at the end of the queue.
- * @return
- * The last <code>Activation</code>.
- */
- public Activation remove() {
- final AgendaItem item = (AgendaItem) this.list.getLast();
- item.remove();
- return item;
- }
-
- /**
- * Remove the given <code>Activation<code> from its place in the queue. This results in the
- * previous <code>Activation</code> being linked to the next <code>activation</code>.
- * @param activation
- * The <code>Activation</code> to be removed.
- */
- public void remove(final Activation activation) {
- this.list.remove( (LinkedListNode) activation );
- }
-
- public LinkedListNode getFirst() {
- return this.list.getFirst();
- }
-
- public Activation[] getActivations() {
- final List activations = new ArrayList( this.list.size() );
- for ( LinkedListNode node = this.list.getFirst(); node != null; node = node.getNext() ) {
- activations.add( node );
- }
- return (Activation[]) activations.toArray( new Activation[activations.size()] );
- }
-
- /**
- * Returns true if there are no <code>Activations</code> on the queue.
- * @return
- * boolean value indicating the empty stae of the queue,
- */
- public boolean isEmpty() {
- return this.list.isEmpty();
- }
-
- public int size() {
- return this.list.size();
- }
-}
Modified: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/AgendaGroupImpl.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/AgendaGroupImpl.java 2006-10-12 23:46:18 UTC (rev 6773)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/AgendaGroupImpl.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -19,8 +19,7 @@
import org.drools.conflict.DepthConflictResolver;
import org.drools.spi.Activation;
import org.drools.spi.AgendaGroup;
-import org.drools.util.BinaryHeapFifoQueue;
-import org.drools.util.PriorityQueue;
+import org.drools.util.BinaryHeapQueue;
import org.drools.util.Queueable;
/**
@@ -44,7 +43,7 @@
private final String name;
/** Items in the agenda. */
- private final BinaryHeapFifoQueue queue;
+ private final BinaryHeapQueue queue;
/**
* Construct an <code>AgendaGroup</code> with the given name.
@@ -54,7 +53,7 @@
*/
public AgendaGroupImpl(final String name) {
this.name = name;
- this.queue = new BinaryHeapFifoQueue( DepthConflictResolver.getInstance() );
+ this.queue = new BinaryHeapQueue( DepthConflictResolver.getInstance() );
}
/* (non-Javadoc)
Modified: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/AgendaItem.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/AgendaItem.java 2006-10-12 23:46:18 UTC (rev 6773)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/AgendaItem.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -160,7 +160,7 @@
return true;
}
- if ( (object == null) || !(object instanceof AgendaItem) ) {
+ if ( object == null || object.getClass() != AgendaItem.class ) {
return false;
}
Modified: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/EqualityAssertMapComparator.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/EqualityAssertMapComparator.java 2006-10-12 23:46:18 UTC (rev 6773)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/EqualityAssertMapComparator.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -1,4 +1,5 @@
package org.drools.common;
+
/*
* Copyright 2005 JBoss Inc
*
@@ -17,7 +18,9 @@
import org.drools.util.AbstractHashTable.ObjectComparator;
-public class EqualityAssertMapComparator extends ObjectComparator {
+public class EqualityAssertMapComparator
+ implements
+ ObjectComparator {
/**
*
*/
@@ -30,8 +33,8 @@
}
public int hashCodeOf(final Object obj) {
- if (obj.getClass() == this.factHandleClass ) {
- return ( ( InternalFactHandle ) obj).getObjectHashCode();
+ if ( obj.getClass() == this.factHandleClass ) {
+ return ((InternalFactHandle) obj).getObjectHashCode();
}
return obj.hashCode();
}
@@ -40,8 +43,8 @@
* Special comparator that allows FactHandles to be keys, but always checks
* equals with the identity of the objects involved
*/
- public boolean areEqual(final Object o1,
- final Object o2) {
+ public boolean equal(final Object o1,
+ final Object o2) {
if ( o1.getClass() == this.factHandleClass ) {
return o1 == o2;
}
Modified: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/IdentityAssertMapComparator.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/IdentityAssertMapComparator.java 2006-10-12 23:46:18 UTC (rev 6773)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/IdentityAssertMapComparator.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -1,4 +1,5 @@
package org.drools.common;
+
/*
* Copyright 2005 JBoss Inc
*
@@ -15,25 +16,25 @@
* limitations under the License.
*/
-import org.drools.util.FastComparator;
+import org.drools.util.AbstractHashTable.ObjectComparator;
-public class IdentityAssertMapComparator extends FastComparator {
+public class IdentityAssertMapComparator
+ implements
+ ObjectComparator {
/**
*
*/
- private static final long serialVersionUID = -4008762903660457691L;
+ private static final long serialVersionUID = 320L;
private final Class factHandleClass;
- private final boolean _rehash = FastComparator.REHASH_SYSTEM_HASHCODE;
-
public IdentityAssertMapComparator(final Class factHandleClass) {
this.factHandleClass = factHandleClass;
}
public int hashCodeOf(final Object obj) {
- if (obj.getClass() == this.factHandleClass ) {
- return ( ( InternalFactHandle ) obj).getObjectHashCode();
+ if ( obj.getClass() == this.factHandleClass ) {
+ return ((InternalFactHandle) obj).getObjectHashCode();
}
return obj.hashCode();
}
@@ -42,12 +43,12 @@
* Special comparator that allows FactHandles to be keys, but always checks
* like for like.
*/
- public boolean areEqual(final Object o1,
- final Object o2) {
+ public boolean equal(final Object o1,
+ final Object o2) {
if ( o1.getClass() == this.factHandleClass ) {
- return ( ( InternalFactHandle ) o1).getObject() == ( ( InternalFactHandle ) o2).getObject();
+ return ((InternalFactHandle) o1).getObject() == ((InternalFactHandle) o2).getObject();
}
-
+
return o1 == ((InternalFactHandle) o2).getObject();
}
Modified: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/RuleFlowNode.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/RuleFlowNode.java 2006-10-12 23:46:18 UTC (rev 6773)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/RuleFlowNode.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -7,7 +7,7 @@
import org.drools.conflict.DepthConflictResolver;
import org.drools.spi.Activation;
import org.drools.spi.AgendaGroup;
-import org.drools.util.BinaryHeapFifoQueue;
+import org.drools.util.BinaryHeapQueue;
import org.drools.util.Queueable;
public class RuleFlowNode
@@ -21,7 +21,7 @@
private final InternalAgenda agenda;
/** @todo Maybe this should just be a LinkedList and we sort on use? */
- private final BinaryHeapFifoQueue queue;
+ private final BinaryHeapQueue queue;
private List childNodes = Collections.EMPTY_LIST;
@@ -37,7 +37,7 @@
final InternalAgenda agenda) {
this.name = name;
this.agenda = agenda;
- this.queue = new BinaryHeapFifoQueue( DepthConflictResolver.getInstance() );
+ this.queue = new BinaryHeapQueue( DepthConflictResolver.getInstance() );
}
/* (non-Javadoc)
Modified: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/TruthMaintenanceSystem.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/TruthMaintenanceSystem.java 2006-10-12 23:46:18 UTC (rev 6773)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/TruthMaintenanceSystem.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -25,7 +25,6 @@
import org.drools.rule.Rule;
import org.drools.spi.Activation;
import org.drools.spi.PropagationContext;
-import org.drools.util.FastMap;
import org.drools.util.ObjectHashMap;
import org.drools.util.PrimitiveLongMap;
Deleted: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/AbstractHashedMap.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/AbstractHashedMap.java 2006-10-12 23:46:18 UTC (rev 6773)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/AbstractHashedMap.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -1,1465 +0,0 @@
-package org.drools.util;
-
-/*
- * Copyright 2005 JBoss Inc
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.util.AbstractCollection;
-import java.util.AbstractMap;
-import java.util.AbstractSet;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.ConcurrentModificationException;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.NoSuchElementException;
-import java.util.Set;
-
-/**
- * An abstract implementation of a hash-based map which provides numerous points
- * for subclasses to override.
- * <p>
- * This class implements all the features necessary for a subclass hash-based
- * map. Key-value entries are stored in instances of the <code>HashEntry</code>
- * class, which can be overridden and replaced. The iterators can similarly be
- * replaced, without the need to replace the KeySet, EntrySet and Values view
- * classes.
- * <p>
- * Overridable methods are provided to change the default hashing behaviour, and
- * to change how entries are added to and removed from the map. Hopefully, all
- * you need for unusual subclasses is here.
- * <p>
- * NOTE: From Commons Collections 3.1 this class extends AbstractMap. This is to
- * provide backwards compatibility for ReferenceMap between v3.0 and v3.1. This
- * extends clause will be removed in v4.0.
- *
- * @since Commons Collections 3.0
- * @version $Revision: 1.1 $ $Date: 2005/07/26 01:06:32 $
- *
- * @author java util HashMap
- * @author Stephen Colebourne
- */
-public class AbstractHashedMap extends AbstractMap {
-
- protected static final String NO_NEXT_ENTRY = "No next() entry in the iteration";
- protected static final String NO_PREVIOUS_ENTRY = "No previous() entry in the iteration";
- protected static final String REMOVE_INVALID = "remove() can only be called once after next()";
- protected static final String GETKEY_INVALID = "getKey() can only be called after next() and before remove()";
- protected static final String GETVALUE_INVALID = "getValue() can only be called after next() and before remove()";
- protected static final String SETVALUE_INVALID = "setValue() can only be called after next() and before remove()";
-
- /** The default capacity to use */
- protected static final int DEFAULT_CAPACITY = 16;
- /** The default threshold to use */
- protected static final int DEFAULT_THRESHOLD = 12;
- /** The default load factor to use */
- protected static final float DEFAULT_LOAD_FACTOR = 0.75f;
- /** The maximum capacity allowed */
- protected static final int MAXIMUM_CAPACITY = 1 << 30;
- /** An object for masking null */
- protected static final Object NULL = new Object();
-
- /** Load factor, normally 0.75 */
- protected transient float loadFactor;
- /** The size of the map */
- protected transient int size;
- /** Map entries */
- protected transient HashEntry[] data;
- /** Size at which to rehash */
- protected transient int threshold;
- /** Modification count for iterators */
- protected transient int modCount;
- /** Entry set */
- protected transient EntrySet entrySet;
- /** Key set */
- protected transient KeySet keySet;
- /** Values */
- protected transient Values values;
-
- /**
- * Constructor only used in deserialization, do not use otherwise.
- */
- protected AbstractHashedMap() {
- super();
- }
-
- /**
- * Constructor which performs no validation on the passed in parameters.
- *
- * @param initialCapacity
- * the initial capacity, must be a power of two
- * @param loadFactor
- * the load factor, must be > 0.0f and generally < 1.0f
- * @param threshold
- * the threshold, must be sensible
- */
- protected AbstractHashedMap(final int initialCapacity,
- final float loadFactor,
- final int threshold) {
- super();
- this.loadFactor = loadFactor;
- this.data = new HashEntry[initialCapacity];
- this.threshold = threshold;
- init();
- }
-
- /**
- * Constructs a new, empty map with the specified initial capacity and
- * default load factor.
- *
- * @param initialCapacity
- * the initial capacity
- * @throws IllegalArgumentException
- * if the initial capacity is less than one
- */
- protected AbstractHashedMap(final int initialCapacity) {
- this( initialCapacity,
- AbstractHashedMap.DEFAULT_LOAD_FACTOR );
- }
-
- /**
- * Constructs a new, empty map with the specified initial capacity and load
- * factor.
- *
- * @param initialCapacity
- * the initial capacity
- * @param loadFactor
- * the load factor
- * @throws IllegalArgumentException
- * if the initial capacity is less than one
- * @throws IllegalArgumentException
- * if the load factor is less than or equal to zero
- */
- protected AbstractHashedMap(int initialCapacity,
- final float loadFactor) {
- super();
- if ( initialCapacity < 1 ) {
- throw new IllegalArgumentException( "Initial capacity must be greater than 0" );
- }
- if ( loadFactor <= 0.0f || Float.isNaN( loadFactor ) ) {
- throw new IllegalArgumentException( "Load factor must be greater than 0" );
- }
- this.loadFactor = loadFactor;
- this.threshold = calculateThreshold( initialCapacity,
- loadFactor );
- initialCapacity = calculateNewCapacity( initialCapacity );
- this.data = new HashEntry[initialCapacity];
- init();
- }
-
- /**
- * Constructor copying elements from another map.
- *
- * @param map
- * the map to copy
- * @throws NullPointerException
- * if the map is null
- */
- protected AbstractHashedMap(final Map map) {
- this( Math.max( 2 * map.size(),
- AbstractHashedMap.DEFAULT_CAPACITY ),
- AbstractHashedMap.DEFAULT_LOAD_FACTOR );
- putAll( map );
- }
-
- /**
- * Initialise subclasses during construction, cloning or deserialization.
- */
- protected void init() {
- }
-
- // -----------------------------------------------------------------------
- /**
- * Gets the value mapped to the key specified.
- *
- * @param key
- * the key
- * @return the mapped value, null if no match
- */
- public Object get(Object key) {
- key = convertKey( key );
- final int hashCode = hash( key );
- HashEntry entry = this.data[hashIndex( hashCode,
- this.data.length )]; // no local
- // for hash
- // index
- while ( entry != null ) {
- if ( entry.hashCode == hashCode && isEqualKey( key,
- entry.key ) ) {
- return entry.getValue();
- }
- entry = entry.next;
- }
- return null;
- }
-
- /**
- * Gets the size of the map.
- *
- * @return the size
- */
- public int size() {
- return this.size;
- }
-
- /**
- * Checks whether the map is currently empty.
- *
- * @return true if the map is currently size zero
- */
- public boolean isEmpty() {
- return (this.size == 0);
- }
-
- // -----------------------------------------------------------------------
- /**
- * Checks whether the map contains the specified key.
- *
- * @param key
- * the key to search for
- * @return true if the map contains the key
- */
- public boolean containsKey(Object key) {
- key = convertKey( key );
- final int hashCode = hash( key );
- HashEntry entry = this.data[hashIndex( hashCode,
- this.data.length )]; // no local
- // for hash
- // index
- while ( entry != null ) {
- if ( entry.hashCode == hashCode && isEqualKey( key,
- entry.key ) ) {
- return true;
- }
- entry = entry.next;
- }
- return false;
- }
-
- /**
- * Checks whether the map contains the specified value.
- *
- * @param value
- * the value to search for
- * @return true if the map contains the value
- */
- public boolean containsValue(final Object value) {
- if ( value == null ) {
- for ( int i = 0, isize = this.data.length; i < isize; i++ ) {
- HashEntry entry = this.data[i];
- while ( entry != null ) {
- if ( entry.getValue() == null ) {
- return true;
- }
- entry = entry.next;
- }
- }
- } else {
- for ( int i = 0, isize = this.data.length; i < isize; i++ ) {
- HashEntry entry = this.data[i];
- while ( entry != null ) {
- if ( isEqualValue( value,
- entry.getValue() ) ) {
- return true;
- }
- entry = entry.next;
- }
- }
- }
- return false;
- }
-
- // -----------------------------------------------------------------------
- /**
- * Puts a key-value mapping into this map.
- *
- * @param key
- * the key to add
- * @param value
- * the value to add
- * @return the value previously mapped to this key, null if none
- */
- public Object put(Object key,
- final Object value) {
- key = convertKey( key );
- final int hashCode = hash( key );
- final int index = hashIndex( hashCode,
- this.data.length );
- HashEntry entry = this.data[index];
- while ( entry != null ) {
- if ( entry.hashCode == hashCode && isEqualKey( key,
- entry.key ) ) {
- final Object oldValue = entry.getValue();
- updateEntry( entry,
- value );
- return oldValue;
- }
- entry = entry.next;
- }
-
- addMapping( index,
- hashCode,
- key,
- value );
- return null;
- }
-
- /**
- * Puts all the values from the specified map into this map.
- * <p>
- * This implementation iterates around the specified map and uses
- * {@link #put(Object, Object)}.
- *
- * @param map
- * the map to add
- * @throws NullPointerException
- * if the map is null
- */
- public void putAll(final Map map) {
- final int mapSize = map.size();
- if ( mapSize == 0 ) {
- return;
- }
- final int newSize = (int) ((this.size + mapSize) / this.loadFactor + 1);
- ensureCapacity( calculateNewCapacity( newSize ) );
- for ( final Iterator it = map.entrySet().iterator(); it.hasNext(); ) {
- final Map.Entry entry = (Map.Entry) it.next();
- put( entry.getKey(),
- entry.getValue() );
- }
- }
-
- /**
- * Removes the specified mapping from this map.
- *
- * @param key
- * the mapping to remove
- * @return the value mapped to the removed key, null if key not in map
- */
- public Object remove(Object key) {
- key = convertKey( key );
- final int hashCode = hash( key );
- final int index = hashIndex( hashCode,
- this.data.length );
- HashEntry entry = this.data[index];
- HashEntry previous = null;
- while ( entry != null ) {
- if ( entry.hashCode == hashCode && isEqualKey( key,
- entry.key ) ) {
- final Object oldValue = entry.getValue();
- removeMapping( entry,
- index,
- previous );
- return oldValue;
- }
- previous = entry;
- entry = entry.next;
- }
- return null;
- }
-
- /**
- * Clears the map, resetting the size to zero and nullifying references to
- * avoid garbage collection issues.
- */
- public void clear() {
- this.modCount++;
- final HashEntry[] data = this.data;
- for ( int i = data.length - 1; i >= 0; i-- ) {
- data[i] = null;
- }
- this.size = 0;
- }
-
- // -----------------------------------------------------------------------
- /**
- * Converts input keys to another object for storage in the map. This
- * implementation masks nulls. Subclasses can override this to perform
- * alternate key conversions.
- * <p>
- * The reverse conversion can be changed, if required, by overriding the
- * getKey() method in the hash entry.
- *
- * @param key
- * the key convert
- * @return the converted key
- */
- protected Object convertKey(final Object key) {
- return (key == null ? AbstractHashedMap.NULL : key);
- }
-
- /**
- * Gets the hash code for the key specified. This implementation uses the
- * additional hashing routine from JDK1.4. Subclasses can override this to
- * return alternate hash codes.
- *
- * @param key
- * the key to get a hash code for
- * @return the hash code
- */
- protected int hash(final Object key) {
- // same as JDK 1.4
- int h = key.hashCode();
- h += ~(h << 9);
- h ^= (h >>> 14);
- h += (h << 4);
- h ^= (h >>> 10);
- return h;
- }
-
- /**
- * Compares two keys, in internal converted form, to see if they are equal.
- * This implementation uses the equals method and assumes neither key is
- * null. Subclasses can override this to match differently.
- *
- * @param key1
- * the first key to compare passed in from outside
- * @param key2
- * the second key extracted from the entry via
- * <code>entry.key</code>
- * @return true if equal
- */
- protected boolean isEqualKey(final Object key1,
- final Object key2) {
- return (key1 == key2 || key1.equals( key2 ));
- }
-
- /**
- * Compares two values, in external form, to see if they are equal. This
- * implementation uses the equals method and assumes neither value is null.
- * Subclasses can override this to match differently.
- *
- * @param value1
- * the first value to compare passed in from outside
- * @param value2
- * the second value extracted from the entry via
- * <code>getValue()</code>
- * @return true if equal
- */
- protected boolean isEqualValue(final Object value1,
- final Object value2) {
- return (value1 == value2 || value1.equals( value2 ));
- }
-
- /**
- * Gets the index into the data storage for the hashCode specified. This
- * implementation uses the least significant bits of the hashCode.
- * Subclasses can override this to return alternate bucketing.
- *
- * @param hashCode
- * the hash code to use
- * @param dataSize
- * the size of the data to pick a bucket from
- * @return the bucket index
- */
- protected int hashIndex(final int hashCode,
- final int dataSize) {
- return hashCode & (dataSize - 1);
- }
-
- // -----------------------------------------------------------------------
- /**
- * Gets the entry mapped to the key specified.
- * <p>
- * This method exists for subclasses that may need to perform a multi-step
- * process accessing the entry. The public methods in this class don't use
- * this method to gain a small performance boost.
- *
- * @param key
- * the key
- * @return the entry, null if no match
- */
- protected HashEntry getEntry(Object key) {
- key = convertKey( key );
- final int hashCode = hash( key );
- HashEntry entry = this.data[hashIndex( hashCode,
- this.data.length )]; // no local
- // for hash
- // index
- while ( entry != null ) {
- if ( entry.hashCode == hashCode && isEqualKey( key,
- entry.key ) ) {
- return entry;
- }
- entry = entry.next;
- }
- return null;
- }
-
- // -----------------------------------------------------------------------
- /**
- * Updates an existing key-value mapping to change the value.
- * <p>
- * This implementation calls <code>setValue()</code> on the entry.
- * Subclasses could override to handle changes to the map.
- *
- * @param entry
- * the entry to update
- * @param newValue
- * the new value to store
- */
- protected void updateEntry(final HashEntry entry,
- final Object newValue) {
- entry.setValue( newValue );
- }
-
- /**
- * Reuses an existing key-value mapping, storing completely new data.
- * <p>
- * This implementation sets all the data fields on the entry. Subclasses
- * could populate additional entry fields.
- *
- * @param entry
- * the entry to update, not null
- * @param hashIndex
- * the index in the data array
- * @param hashCode
- * the hash code of the key to add
- * @param key
- * the key to add
- * @param value
- * the value to add
- */
- protected void reuseEntry(final HashEntry entry,
- final int hashIndex,
- final int hashCode,
- final Object key,
- final Object value) {
- entry.next = this.data[hashIndex];
- entry.hashCode = hashCode;
- entry.key = key;
- entry.value = value;
- }
-
- // -----------------------------------------------------------------------
- /**
- * Adds a new key-value mapping into this map.
- * <p>
- * This implementation calls <code>createEntry()</code>,
- * <code>addEntry()</code> and <code>checkCapacity()</code>. It also
- * handles changes to <code>modCount</code> and <code>size</code>.
- * Subclasses could override to fully control adds to the map.
- *
- * @param hashIndex
- * the index into the data array to store at
- * @param hashCode
- * the hash code of the key to add
- * @param key
- * the key to add
- * @param value
- * the value to add
- */
- protected void addMapping(final int hashIndex,
- final int hashCode,
- final Object key,
- final Object value) {
- this.modCount++;
- final HashEntry entry = createEntry( this.data[hashIndex],
- hashCode,
- key,
- value );
- addEntry( entry,
- hashIndex );
- this.size++;
- checkCapacity();
- }
-
- /**
- * Creates an entry to store the key-value data.
- * <p>
- * This implementation creates a new HashEntry instance. Subclasses can
- * override this to return a different storage class, or implement caching.
- *
- * @param next
- * the next entry in sequence
- * @param hashCode
- * the hash code to use
- * @param key
- * the key to store
- * @param value
- * the value to store
- * @return the newly created entry
- */
- protected HashEntry createEntry(final HashEntry next,
- final int hashCode,
- final Object key,
- final Object value) {
- return new HashEntry( next,
- hashCode,
- key,
- value );
- }
-
- /**
- * Adds an entry into this map.
- * <p>
- * This implementation adds the entry to the data storage table. Subclasses
- * could override to handle changes to the map.
- *
- * @param entry
- * the entry to add
- * @param hashIndex
- * the index into the data array to store at
- */
- protected void addEntry(final HashEntry entry,
- final int hashIndex) {
- this.data[hashIndex] = entry;
- }
-
- // -----------------------------------------------------------------------
- /**
- * Removes a mapping from the map.
- * <p>
- * This implementation calls <code>removeEntry()</code> and
- * <code>destroyEntry()</code>. It also handles changes to
- * <code>modCount</code> and <code>size</code>. Subclasses could
- * override to fully control removals from the map.
- *
- * @param entry
- * the entry to remove
- * @param hashIndex
- * the index into the data structure
- * @param previous
- * the previous entry in the chain
- */
- protected void removeMapping(final HashEntry entry,
- final int hashIndex,
- final HashEntry previous) {
- this.modCount++;
- removeEntry( entry,
- hashIndex,
- previous );
- this.size--;
- destroyEntry( entry );
- }
-
- /**
- * Removes an entry from the chain stored in a particular index.
- * <p>
- * This implementation removes the entry from the data storage table. The
- * size is not updated. Subclasses could override to handle changes to the
- * map.
- *
- * @param entry
- * the entry to remove
- * @param hashIndex
- * the index into the data structure
- * @param previous
- * the previous entry in the chain
- */
- protected void removeEntry(final HashEntry entry,
- final int hashIndex,
- final HashEntry previous) {
- if ( previous == null ) {
- this.data[hashIndex] = entry.next;
- } else {
- previous.next = entry.next;
- }
- }
-
- /**
- * Kills an entry ready for the garbage collector.
- * <p>
- * This implementation prepares the HashEntry for garbage collection.
- * Subclasses can override this to implement caching (override clear as
- * well).
- *
- * @param entry
- * the entry to destroy
- */
- protected void destroyEntry(final HashEntry entry) {
- entry.next = null;
- entry.key = null;
- entry.value = null;
- }
-
- // -----------------------------------------------------------------------
- /**
- * Checks the capacity of the map and enlarges it if necessary.
- * <p>
- * This implementation uses the threshold to check if the map needs
- * enlarging
- */
- protected void checkCapacity() {
- if ( this.size >= this.threshold ) {
- final int newCapacity = this.data.length * 2;
- if ( newCapacity <= AbstractHashedMap.MAXIMUM_CAPACITY ) {
- ensureCapacity( newCapacity );
- }
- }
- }
-
- /**
- * Changes the size of the data structure to the capacity proposed.
- *
- * @param newCapacity
- * the new capacity of the array (a power of two, less or equal
- * to max)
- */
- protected void ensureCapacity(final int newCapacity) {
- final int oldCapacity = this.data.length;
- if ( newCapacity <= oldCapacity ) {
- return;
- }
- if ( this.size == 0 ) {
- this.threshold = calculateThreshold( newCapacity,
- this.loadFactor );
- this.data = new HashEntry[newCapacity];
- } else {
- final HashEntry oldEntries[] = this.data;
- final HashEntry newEntries[] = new HashEntry[newCapacity];
-
- this.modCount++;
- for ( int i = oldCapacity - 1; i >= 0; i-- ) {
- HashEntry entry = oldEntries[i];
- if ( entry != null ) {
- oldEntries[i] = null; // gc
- do {
- final HashEntry next = entry.next;
- final int index = hashIndex( entry.hashCode,
- newCapacity );
- entry.next = newEntries[index];
- newEntries[index] = entry;
- entry = next;
- } while ( entry != null );
- }
- }
- this.threshold = calculateThreshold( newCapacity,
- this.loadFactor );
- this.data = newEntries;
- }
- }
-
- /**
- * Calculates the new capacity of the map. This implementation normalizes
- * the capacity to a power of two.
- *
- * @param proposedCapacity
- * the proposed capacity
- * @return the normalized new capacity
- */
- protected int calculateNewCapacity(final int proposedCapacity) {
- int newCapacity = 1;
- if ( proposedCapacity > AbstractHashedMap.MAXIMUM_CAPACITY ) {
- newCapacity = AbstractHashedMap.MAXIMUM_CAPACITY;
- } else {
- while ( newCapacity < proposedCapacity ) {
- newCapacity <<= 1; // multiply by two
- }
- if ( newCapacity > AbstractHashedMap.MAXIMUM_CAPACITY ) {
- newCapacity = AbstractHashedMap.MAXIMUM_CAPACITY;
- }
- }
- return newCapacity;
- }
-
- /**
- * Calculates the new threshold of the map, where it will be resized. This
- * implementation uses the load factor.
- *
- * @param newCapacity
- * the new capacity
- * @param factor
- * the load factor
- * @return the new resize threshold
- */
- protected int calculateThreshold(final int newCapacity,
- final float factor) {
- return (int) (newCapacity * factor);
- }
-
- // -----------------------------------------------------------------------
- /**
- * Gets the <code>next</code> field from a <code>HashEntry</code>. Used
- * in subclasses that have no visibility of the field.
- *
- * @param entry
- * the entry to query, must not be null
- * @return the <code>next</code> field of the entry
- * @throws NullPointerException
- * if the entry is null
- * @since Commons Collections 3.1
- */
- protected HashEntry entryNext(final HashEntry entry) {
- return entry.next;
- }
-
- /**
- * Gets the <code>hashCode</code> field from a <code>HashEntry</code>.
- * Used in subclasses that have no visibility of the field.
- *
- * @param entry
- * the entry to query, must not be null
- * @return the <code>hashCode</code> field of the entry
- * @throws NullPointerException
- * if the entry is null
- * @since Commons Collections 3.1
- */
- protected int entryHashCode(final HashEntry entry) {
- return entry.hashCode;
- }
-
- /**
- * Gets the <code>key</code> field from a <code>HashEntry</code>. Used
- * in subclasses that have no visibility of the field.
- *
- * @param entry
- * the entry to query, must not be null
- * @return the <code>key</code> field of the entry
- * @throws NullPointerException
- * if the entry is null
- * @since Commons Collections 3.1
- */
- protected Object entryKey(final HashEntry entry) {
- return entry.key;
- }
-
- /**
- * Gets the <code>value</code> field from a <code>HashEntry</code>.
- * Used in subclasses that have no visibility of the field.
- *
- * @param entry
- * the entry to query, must not be null
- * @return the <code>value</code> field of the entry
- * @throws NullPointerException
- * if the entry is null
- * @since Commons Collections 3.1
- */
- protected Object entryValue(final HashEntry entry) {
- return entry.value;
- }
-
- // -----------------------------------------------------------------------
- /**
- * Gets an iterator over the map. Changes made to the iterator affect this
- * map.
- * <p>
- * A MapIterator returns the keys in the map. It also provides convenient
- * methods to get the key and value, and set the value. It avoids the need
- * to create an entrySet/keySet/values object. It also avoids creating the
- * Map.Entry object.
- *
- * @return the map iterator
- */
- private MapIterator mapIterator() {
- if ( this.size == 0 ) {
- return EmptyMapIterator.INSTANCE;
- }
- return new HashMapIterator( this );
- }
-
- /**
- * MapIterator implementation.
- */
- protected static class HashMapIterator extends HashIterator
- implements
- MapIterator {
-
- protected HashMapIterator(final AbstractHashedMap parent) {
- super( parent );
- }
-
- public Object next() {
- return super.nextEntry().getKey();
- }
-
- public Object getKey() {
- final HashEntry current = currentEntry();
- if ( current == null ) {
- throw new IllegalStateException( AbstractHashedMap.GETKEY_INVALID );
- }
- return current.getKey();
- }
-
- public Object getValue() {
- final HashEntry current = currentEntry();
- if ( current == null ) {
- throw new IllegalStateException( AbstractHashedMap.GETVALUE_INVALID );
- }
- return current.getValue();
- }
-
- public Object setValue(final Object value) {
- final HashEntry current = currentEntry();
- if ( current == null ) {
- throw new IllegalStateException( AbstractHashedMap.SETVALUE_INVALID );
- }
- return current.setValue( value );
- }
- }
-
- // -----------------------------------------------------------------------
- /**
- * Gets the entrySet view of the map. Changes made to the view affect this
- * map. To simply iterate through the entries, use {@link #mapIterator()}.
- *
- * @return the entrySet view
- */
- public Set entrySet() {
- if ( this.entrySet == null ) {
- this.entrySet = new EntrySet( this );
- }
- return this.entrySet;
- }
-
- /**
- * Creates an entry set iterator. Subclasses can override this to return
- * iterators with different properties.
- *
- * @return the entrySet iterator
- */
- protected Iterator createEntrySetIterator() {
- if ( size() == 0 ) {
- return Collections.EMPTY_MAP.keySet().iterator();
- }
- return new EntrySetIterator( this );
- }
-
- /**
- * EntrySet implementation.
- */
- protected static class EntrySet extends AbstractSet {
- /** The parent map */
- protected final AbstractHashedMap parent;
-
- protected EntrySet(final AbstractHashedMap parent) {
- super();
- this.parent = parent;
- }
-
- public int size() {
- return this.parent.size();
- }
-
- public void clear() {
- this.parent.clear();
- }
-
- public boolean contains(final Object entry) {
- if ( entry instanceof Map.Entry ) {
- final Map.Entry e = (Map.Entry) entry;
- final Entry match = this.parent.getEntry( e.getKey() );
- return (match != null && match.equals( e ));
- }
- return false;
- }
-
- public boolean remove(final Object obj) {
- if ( obj instanceof Map.Entry == false ) {
- return false;
- }
- if ( contains( obj ) == false ) {
- return false;
- }
- final Map.Entry entry = (Map.Entry) obj;
- final Object key = entry.getKey();
- this.parent.remove( key );
- return true;
- }
-
- public Iterator iterator() {
- return this.parent.createEntrySetIterator();
- }
- }
-
- /**
- * EntrySet iterator.
- */
- protected static class EntrySetIterator extends HashIterator {
-
- protected EntrySetIterator(final AbstractHashedMap parent) {
- super( parent );
- }
-
- public Object next() {
- return super.nextEntry();
- }
- }
-
- // -----------------------------------------------------------------------
- /**
- * Gets the keySet view of the map. Changes made to the view affect this
- * map. To simply iterate through the keys, use {@link #mapIterator()}.
- *
- * @return the keySet view
- */
- public Set keySet() {
- if ( this.keySet == null ) {
- this.keySet = new KeySet( this );
- }
- return this.keySet;
- }
-
- /**
- * Creates a key set iterator. Subclasses can override this to return
- * iterators with different properties.
- *
- * @return the keySet iterator
- */
- protected Iterator createKeySetIterator() {
- if ( size() == 0 ) {
- return Collections.EMPTY_MAP.keySet().iterator();
- }
- return new KeySetIterator( this );
- }
-
- /**
- * KeySet implementation.
- */
- protected static class KeySet extends AbstractSet {
- /** The parent map */
- protected final AbstractHashedMap parent;
-
- protected KeySet(final AbstractHashedMap parent) {
- super();
- this.parent = parent;
- }
-
- public int size() {
- return this.parent.size();
- }
-
- public void clear() {
- this.parent.clear();
- }
-
- public boolean contains(final Object key) {
- return this.parent.containsKey( key );
- }
-
- public boolean remove(final Object key) {
- final boolean result = this.parent.containsKey( key );
- this.parent.remove( key );
- return result;
- }
-
- public Iterator iterator() {
- return this.parent.createKeySetIterator();
- }
- }
-
- /**
- * KeySet iterator.
- */
- protected static class KeySetIterator extends EntrySetIterator {
-
- protected KeySetIterator(final AbstractHashedMap parent) {
- super( parent );
- }
-
- public Object next() {
- return super.nextEntry().getKey();
- }
- }
-
- // -----------------------------------------------------------------------
- /**
- * Gets the values view of the map. Changes made to the view affect this
- * map. To simply iterate through the values, use {@link #mapIterator()}.
- *
- * @return the values view
- */
- public Collection values() {
- if ( this.values == null ) {
- this.values = new Values( this );
- }
- return this.values;
- }
-
- /**
- * Creates a values iterator. Subclasses can override this to return
- * iterators with different properties.
- *
- * @return the values iterator
- */
- protected Iterator createValuesIterator() {
- if ( size() == 0 ) {
- return Collections.EMPTY_MAP.keySet().iterator();
- }
- return new ValuesIterator( this );
- }
-
- /**
- * Values implementation.
- */
- protected static class Values extends AbstractCollection {
- /** The parent map */
- protected final AbstractHashedMap parent;
-
- protected Values(final AbstractHashedMap parent) {
- super();
- this.parent = parent;
- }
-
- public int size() {
- return this.parent.size();
- }
-
- public void clear() {
- this.parent.clear();
- }
-
- public boolean contains(final Object value) {
- return this.parent.containsValue( value );
- }
-
- public Iterator iterator() {
- return this.parent.createValuesIterator();
- }
- }
-
- /**
- * Values iterator.
- */
- protected static class ValuesIterator extends HashIterator {
-
- protected ValuesIterator(final AbstractHashedMap parent) {
- super( parent );
- }
-
- public Object next() {
- return super.nextEntry().getValue();
- }
- }
-
- // -----------------------------------------------------------------------
- /**
- * HashEntry used to store the data.
- * <p>
- * If you subclass <code>AbstractHashedMap</code> but not
- * <code>HashEntry</code> then you will not be able to access the
- * protected fields. The <code>entryXxx()</code> methods on
- * <code>AbstractHashedMap</code> exist to provide the necessary access.
- */
- protected static class HashEntry
- implements
- Map.Entry {
- /** The next entry in the hash chain */
- protected HashEntry next;
- /** The hash code of the key */
- protected int hashCode;
- /** The key */
- protected Object key;
- /** The value */
- protected Object value;
-
- protected HashEntry(final HashEntry next,
- final int hashCode,
- final Object key,
- final Object value) {
- super();
- this.next = next;
- this.hashCode = hashCode;
- this.key = key;
- this.value = value;
- }
-
- public Object getKey() {
- return (this.key == AbstractHashedMap.NULL ? null : this.key);
- }
-
- public Object getValue() {
- return this.value;
- }
-
- public Object setValue(final Object value) {
- final Object old = this.value;
- this.value = value;
- return old;
- }
-
- public boolean equals(final Object obj) {
- if ( obj == this ) {
- return true;
- }
- if ( obj instanceof Map.Entry == false ) {
- return false;
- }
- final Map.Entry other = (Map.Entry) obj;
- return (getKey() == null ? other.getKey() == null : getKey().equals( other.getKey() )) && (getValue() == null ? other.getValue() == null : getValue().equals( other.getValue() ));
- }
-
- public int hashCode() {
- return (getKey() == null ? 0 : getKey().hashCode()) ^ (getValue() == null ? 0 : getValue().hashCode());
- }
-
- public String toString() {
- return new StringBuffer().append( getKey() ).append( '=' ).append( getValue() ).toString();
- }
- }
-
- /**
- * Base Iterator
- */
- protected static abstract class HashIterator
- implements
- Iterator {
-
- /** The parent map */
- protected final AbstractHashedMap parent;
- /** The current index into the array of buckets */
- protected int hashIndex;
- /** The last returned entry */
- protected HashEntry last;
- /** The next entry */
- protected HashEntry next;
- /** The modification count expected */
- protected int expectedModCount;
-
- protected HashIterator(final AbstractHashedMap parent) {
- super();
- this.parent = parent;
- final HashEntry[] data = parent.data;
- int i = data.length;
- HashEntry next = null;
- while ( i > 0 && next == null ) {
- next = data[--i];
- }
- this.next = next;
- this.hashIndex = i;
- this.expectedModCount = parent.modCount;
- }
-
- public boolean hasNext() {
- return (this.next != null);
- }
-
- protected HashEntry nextEntry() {
- if ( this.parent.modCount != this.expectedModCount ) {
- throw new ConcurrentModificationException();
- }
- final HashEntry newCurrent = this.next;
- if ( newCurrent == null ) {
- throw new NoSuchElementException( AbstractHashedMap.NO_NEXT_ENTRY );
- }
- final HashEntry[] data = this.parent.data;
- int i = this.hashIndex;
- HashEntry n = newCurrent.next;
- while ( n == null && i > 0 ) {
- n = data[--i];
- }
- this.next = n;
- this.hashIndex = i;
- this.last = newCurrent;
- return newCurrent;
- }
-
- protected HashEntry currentEntry() {
- return this.last;
- }
-
- public void remove() {
- if ( this.last == null ) {
- throw new IllegalStateException( AbstractHashedMap.REMOVE_INVALID );
- }
- if ( this.parent.modCount != this.expectedModCount ) {
- throw new ConcurrentModificationException();
- }
- this.parent.remove( this.last.getKey() );
- this.last = null;
- this.expectedModCount = this.parent.modCount;
- }
-
- public String toString() {
- if ( this.last != null ) {
- return "Iterator[" + this.last.getKey() + "=" + this.last.getValue() + "]";
- } else {
- return "Iterator[]";
- }
- }
- }
-
- // -----------------------------------------------------------------------
- /**
- * Writes the map data to the stream. This method must be overridden if a
- * subclass must be setup before <code>put()</code> is used.
- * <p>
- * Serialization is not one of the JDK's nicest topics. Normal serialization
- * will initialise the superclass before the subclass. Sometimes however,
- * this isn't what you want, as in this case the <code>put()</code> method
- * on read can be affected by subclass state.
- * <p>
- * The solution adopted here is to serialize the state data of this class in
- * this protected method. This method must be called by the
- * <code>writeObject()</code> of the first serializable subclass.
- * <p>
- * Subclasses may override if they have a specific field that must be
- * present on read before this implementation will work. Generally, the read
- * determines what must be serialized here, if anything.
- *
- * @param out
- * the output stream
- */
- protected void doWriteObject(final ObjectOutputStream out) throws IOException {
- out.writeFloat( this.loadFactor );
- out.writeInt( this.data.length );
- out.writeInt( this.size );
- for ( final MapIterator it = mapIterator(); it.hasNext(); ) {
- out.writeObject( it.next() );
- out.writeObject( it.getValue() );
- }
- }
-
- /**
- * Reads the map data from the stream. This method must be overridden if a
- * subclass must be setup before <code>put()</code> is used.
- * <p>
- * Serialization is not one of the JDK's nicest topics. Normal serialization
- * will initialise the superclass before the subclass. Sometimes however,
- * this isn't what you want, as in this case the <code>put()</code> method
- * on read can be affected by subclass state.
- * <p>
- * The solution adopted here is to deserialize the state data of this class
- * in this protected method. This method must be called by the
- * <code>readObject()</code> of the first serializable subclass.
- * <p>
- * Subclasses may override if the subclass has a specific field that must be
- * present before <code>put()</code> or <code>calculateThreshold()</code>
- * will work correctly.
- *
- * @param in
- * the input stream
- */
- protected void doReadObject(final ObjectInputStream in) throws IOException,
- ClassNotFoundException {
- this.loadFactor = in.readFloat();
- final int capacity = in.readInt();
- final int size = in.readInt();
- init();
- this.data = new HashEntry[capacity];
- for ( int i = 0; i < size; i++ ) {
- final Object key = in.readObject();
- final Object value = in.readObject();
- put( key,
- value );
- }
- this.threshold = calculateThreshold( this.data.length,
- this.loadFactor );
- }
-
- // -----------------------------------------------------------------------
- /**
- * Clones the map without cloning the keys or values.
- * <p>
- * To implement <code>clone()</code>, a subclass must implement the
- * <code>Cloneable</code> interface and make this method public.
- *
- * @return a shallow clone
- */
- protected Object clone() {
- try {
- final AbstractHashedMap cloned = (AbstractHashedMap) super.clone();
- cloned.data = new HashEntry[this.data.length];
- cloned.entrySet = null;
- cloned.keySet = null;
- cloned.values = null;
- cloned.modCount = 0;
- cloned.size = 0;
- cloned.init();
- cloned.putAll( this );
- return cloned;
-
- } catch ( final CloneNotSupportedException ex ) {
- return null; // should never happen
- }
- }
-
- /**
- * Compares this map with another.
- *
- * @param obj
- * the object to compare to
- * @return true if equal
- */
- public boolean equals(final Object obj) {
- if ( obj == this ) {
- return true;
- }
- if ( obj instanceof Map == false ) {
- return false;
- }
- final Map map = (Map) obj;
- if ( map.size() != size() ) {
- return false;
- }
- final MapIterator it = mapIterator();
- try {
- while ( it.hasNext() ) {
- final Object key = it.next();
- final Object value = it.getValue();
- if ( value == null ) {
- if ( map.get( key ) != null || map.containsKey( key ) == false ) {
- return false;
- }
- } else {
- if ( value.equals( map.get( key ) ) == false ) {
- return false;
- }
- }
- }
- } catch ( final ClassCastException ignored ) {
- return false;
- } catch ( final NullPointerException ignored ) {
- return false;
- }
- return true;
- }
-
- /**
- * Gets the standard Map hashCode.
- *
- * @return the hash code defined in the Map interface
- */
- public int hashCode() {
- int total = 0;
- final Iterator it = createEntrySetIterator();
- while ( it.hasNext() ) {
- total += it.next().hashCode();
- }
- return total;
- }
-
- /**
- * Gets the map as a String.
- *
- * @return a string version of the map
- */
- public String toString() {
- if ( size() == 0 ) {
- return "{}";
- }
- final StringBuffer buf = new StringBuffer( 32 * size() );
- buf.append( '{' );
-
- final MapIterator it = mapIterator();
- boolean hasNext = it.hasNext();
- while ( hasNext ) {
- final Object key = it.next();
- final Object value = it.getValue();
- buf.append( key == this ? "(this Map)" : key ).append( '=' ).append( value == this ? "(this Map)" : value );
-
- hasNext = it.hasNext();
- if ( hasNext ) {
- buf.append( ',' ).append( ' ' );
- }
- }
-
- buf.append( '}' );
- return buf.toString();
- }
-}
\ No newline at end of file
Deleted: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/BaseMultiLinkedListNode.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/BaseMultiLinkedListNode.java 2006-10-12 23:46:18 UTC (rev 6773)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/BaseMultiLinkedListNode.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -1,74 +0,0 @@
-/*
- * Copyright 2005 JBoss Inc
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.drools.util;
-
-/**
- * BaseMultiLinkedListNode
- * A base implementation for the MultiLinkedListNode that helps to
- * manage object references.
- *
- * @author <a href="mailto:tirelli at post.com">Edson Tirelli</a>
- *
- * Created: 12/02/2006
- */
-public class BaseMultiLinkedListNode extends AbstractBaseLinkedListNode
- implements
- MultiLinkedListNode {
-
- private MultiLinkedListNode child = null;
- private LinkedList outerList = null;
-
- public BaseMultiLinkedListNode() {
- }
-
- /**
- * @inheritDoc
- *
- * @see org.drools.util.MultiLinkedListNode#getChild()
- */
- public MultiLinkedListNode getChild() {
- return this.child;
- }
-
- /**
- * @inheritDoc
- *
- * @see org.drools.util.MultiLinkedListNode#setChild(org.drools.util.LinkedListNode)
- */
- public void setChild(final MultiLinkedListNode child) {
- this.child = child;
- }
-
- /**
- * @inheritDoc
- *
- * @see org.drools.util.MultiLinkedListNode#getOuterList()
- */
- public LinkedList getOuterList() {
- return this.outerList;
- }
-
- /**
- * @inheritDoc
- *
- * @see org.drools.util.MultiLinkedListNode#setOuterList(org.drools.util.LinkedList)
- */
- public void setOuterList(final LinkedList list) {
- this.outerList = list;
- }
-
-}
Deleted: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/BinaryHeapFifoQueue.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/BinaryHeapFifoQueue.java 2006-10-12 23:46:18 UTC (rev 6773)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/BinaryHeapFifoQueue.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -1,324 +0,0 @@
-package org.drools.util;
-
-/*
- * Copyright 2005 JBoss Inc
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import java.io.Serializable;
-import java.util.Comparator;
-import java.util.NoSuchElementException;
-
-public class BinaryHeapFifoQueue
- implements
- Queue,
- Serializable {
- /** The default capacity for a binary heap. */
- private final static int DEFAULT_CAPACITY = 13;
-
- /** The comparator used to order the elements */
- private final Comparator comparator;
-
- /** The number of elements currently in this heap. */
- private int size;
-
- /** The elements in this heap. */
- private Queueable[] elements;
-
- /**
- * Constructs a new <code>BinaryHeap</code> that will use the given
- * comparator to order its elements.
- *
- * @param comparator the comparator used to order the elements, null
- * means use natural order
- */
- public BinaryHeapFifoQueue(final Comparator comparator) {
- this( comparator,
- BinaryHeapFifoQueue.DEFAULT_CAPACITY );
- }
-
- /**
- * Constructs a new <code>BinaryHeap</code>.
- *
- * @param comparator the comparator used to order the elements, null
- * means use natural order
- * @param capacity the initial capacity for the heap
- * @throws IllegalArgumentException if <code>capacity</code> is <= <code>0</code>
- */
- public BinaryHeapFifoQueue(final Comparator comparator,
- final int capacity) {
- if ( capacity <= 0 ) {
- throw new IllegalArgumentException( "invalid capacity" );
- }
-
- //+1 as 0 is noop
- this.elements = new Queueable[capacity + 1];
- this.comparator = comparator;
- }
-
- //-----------------------------------------------------------------------
-
- /**
- * Clears all elements from queue.
- */
- public void clear() {
- this.elements = new Queueable[this.elements.length]; // for gc
- this.size = 0;
- }
-
- /**
- * Tests if queue is empty.
- *
- * @return <code>true</code> if queue is empty; <code>false</code>
- * otherwise.
- */
- public boolean isEmpty() {
- return this.size == 0;
- }
-
- /**
- * Tests if queue is full.
- *
- * @return <code>true</code> if queue is full; <code>false</code>
- * otherwise.
- */
- public boolean isFull() {
- //+1 as Queueable 0 is noop
- return this.elements.length == this.size + 1;
- }
-
- /**
- * Returns the number of elements in this heap.
- *
- * @return the number of elements in this heap
- */
- public int size() {
- return this.size;
- }
-
- /**
- * Inserts an Queueable into queue.
- *
- * @param element the Queueable to be inserted
- */
- public void enqueue(final Queueable element) {
- if ( isFull() ) {
- grow();
- }
-
- percolateUpMinHeap( element );
- }
-
- /**
- * Returns the Queueable on top of heap and remove it.
- *
- * @return the Queueable at top of heap
- * @throws NoSuchElementException if <code>isEmpty() == true</code>
- */
- public Queueable dequeue() throws NoSuchElementException {
- if ( isEmpty() ) {
- return null;
- }
-
- final Queueable result = this.elements[1];
- result.dequeue();
-
- // Code bellow was removed because it is already executed
- // inside result.dequeue()
- //
- // setElement(1, this.elements[this.size--]);
- // this.elements[this.size + 1] = null;
- //
- // if (this.size != 0) {
- // percolateDownMinHeap(1);
- // }
-
- return result;
- }
-
- /**
- *
- * @param index
- */
- public Queueable dequeue(final int index) {
- if ( index < 1 || index > this.size ) {
- //throw new NoSuchElementException();
- return null;
- }
-
- final Queueable result = this.elements[index];
- setElement( index,
- this.elements[this.size] );
- this.elements[this.size] = null;
- this.size--;
- if ( this.size != 0 && index <= this.size ) {
- int compareToParent = 0;
- if ( index > 1 ) {
- compareToParent = compare( this.elements[index],
- this.elements[index / 2] );
- }
- if ( index > 1 && compareToParent < 0 ) {
- percolateUpMinHeap( index );
- } else {
- percolateDownMinHeap( index );
- }
- }
-
- return result;
- }
-
- /**
- * Percolates Queueable down heap from the position given by the index.
- * <p/>
- * Assumes it is a minimum heap.
- *
- * @param index the index for the Queueable
- */
- private void percolateDownMinHeap(final int index) {
- final Queueable element = this.elements[index];
- int hole = index;
-
- while ( (hole * 2) <= this.size ) {
- int child = hole * 2;
-
- // if we have a right child and that child can not be percolated
- // up then move onto other child
- if ( child != this.size && compare( this.elements[child + 1],
- this.elements[child] ) < 0 ) {
- child++;
- }
-
- // if we found resting place of bubble then terminate search
- if ( compare( this.elements[child],
- element ) >= 0 ) {
- break;
- }
-
- setElement( hole,
- this.elements[child] );
- hole = child;
- }
-
- setElement( hole,
- element );
- }
-
- /**
- * Percolates Queueable up heap from the position given by the index.
- * <p/>
- * Assumes it is a minimum heap.
- *
- * @param index the index of the Queueable to be percolated up
- */
- private void percolateUpMinHeap(final int index) {
- int hole = index;
- final Queueable element = this.elements[hole];
- while ( hole > 1 && compare( element,
- this.elements[hole / 2] ) < 0 ) {
- // save Queueable that is being pushed down
- // as the Queueable "bubble" is percolated up
- final int next = hole / 2;
- setElement( hole,
- this.elements[next] );
- hole = next;
- }
- setElement( hole,
- element );
- }
-
- /**
- * Percolates a new Queueable up heap from the bottom.
- * <p/>
- * Assumes it is a minimum heap.
- *
- * @param element the Queueable
- */
- private void percolateUpMinHeap(final Queueable element) {
- setElement( ++this.size,
- element );
- percolateUpMinHeap( this.size );
- }
-
- /**
- * Compares two objects using the comparator if specified, or the
- * natural order otherwise.
- *
- * @param a the first object
- * @param b the second object
- * @return -ve if a less than b, 0 if they are equal, +ve if a greater than b
- */
- private int compare(final Queueable a,
- final Queueable b) {
- return this.comparator.compare( a,
- b );
- }
-
- /**
- * Increases the size of the heap to support additional elements
- */
- private void grow() {
- final Queueable[] elements = new Queueable[this.elements.length * 2];
- System.arraycopy( this.elements,
- 0,
- elements,
- 0,
- this.elements.length );
- this.elements = elements;
- }
-
- /**
- *
- * @param index
- * @param element
- */
- private void setElement(final int index,
- final Queueable element) {
- this.elements[index] = element;
- element.enqueued( this,
- index );
- }
-
- public Queueable[] getQueueable() {
- return this.elements;
- }
-
- public Object[] toArray() {
- final Object[] result = new Object[this.size];
- System.arraycopy( this.elements,
- 1,
- result,
- 0,
- this.size );
- return result;
- }
-
- public Object[] toArray(Object a[]) {
- if ( a.length < this.size ) {
- a = (Object[]) java.lang.reflect.Array.newInstance( a.getClass().getComponentType(),
- this.size );
- }
-
- System.arraycopy( this.elements,
- 1,
- a,
- 0,
- this.size );
-
- if ( a.length > this.size ) {
- a[this.size] = null;
- }
-
- return a;
- }
-}
\ No newline at end of file
Copied: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/BinaryHeapQueue.java (from rev 6753, labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/BinaryHeapFifoQueue.java)
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/BinaryHeapFifoQueue.java 2006-10-12 12:04:00 UTC (rev 6753)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/BinaryHeapQueue.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -0,0 +1,324 @@
+package org.drools.util;
+
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import java.io.Serializable;
+import java.util.Comparator;
+import java.util.NoSuchElementException;
+
+public class BinaryHeapQueue
+ implements
+ Queue,
+ Serializable {
+ /** The default capacity for a binary heap. */
+ private final static int DEFAULT_CAPACITY = 13;
+
+ /** The comparator used to order the elements */
+ private final Comparator comparator;
+
+ /** The number of elements currently in this heap. */
+ private int size;
+
+ /** The elements in this heap. */
+ private Queueable[] elements;
+
+ /**
+ * Constructs a new <code>BinaryHeap</code> that will use the given
+ * comparator to order its elements.
+ *
+ * @param comparator the comparator used to order the elements, null
+ * means use natural order
+ */
+ public BinaryHeapQueue(final Comparator comparator) {
+ this( comparator,
+ BinaryHeapQueue.DEFAULT_CAPACITY );
+ }
+
+ /**
+ * Constructs a new <code>BinaryHeap</code>.
+ *
+ * @param comparator the comparator used to order the elements, null
+ * means use natural order
+ * @param capacity the initial capacity for the heap
+ * @throws IllegalArgumentException if <code>capacity</code> is <= <code>0</code>
+ */
+ public BinaryHeapQueue(final Comparator comparator,
+ final int capacity) {
+ if ( capacity <= 0 ) {
+ throw new IllegalArgumentException( "invalid capacity" );
+ }
+
+ //+1 as 0 is noop
+ this.elements = new Queueable[capacity + 1];
+ this.comparator = comparator;
+ }
+
+ //-----------------------------------------------------------------------
+
+ /**
+ * Clears all elements from queue.
+ */
+ public void clear() {
+ this.elements = new Queueable[this.elements.length]; // for gc
+ this.size = 0;
+ }
+
+ /**
+ * Tests if queue is empty.
+ *
+ * @return <code>true</code> if queue is empty; <code>false</code>
+ * otherwise.
+ */
+ public boolean isEmpty() {
+ return this.size == 0;
+ }
+
+ /**
+ * Tests if queue is full.
+ *
+ * @return <code>true</code> if queue is full; <code>false</code>
+ * otherwise.
+ */
+ public boolean isFull() {
+ //+1 as Queueable 0 is noop
+ return this.elements.length == this.size + 1;
+ }
+
+ /**
+ * Returns the number of elements in this heap.
+ *
+ * @return the number of elements in this heap
+ */
+ public int size() {
+ return this.size;
+ }
+
+ /**
+ * Inserts an Queueable into queue.
+ *
+ * @param element the Queueable to be inserted
+ */
+ public void enqueue(final Queueable element) {
+ if ( isFull() ) {
+ grow();
+ }
+
+ percolateUpMinHeap( element );
+ }
+
+ /**
+ * Returns the Queueable on top of heap and remove it.
+ *
+ * @return the Queueable at top of heap
+ * @throws NoSuchElementException if <code>isEmpty() == true</code>
+ */
+ public Queueable dequeue() throws NoSuchElementException {
+ if ( isEmpty() ) {
+ return null;
+ }
+
+ final Queueable result = this.elements[1];
+ result.dequeue();
+
+ // Code bellow was removed because it is already executed
+ // inside result.dequeue()
+ //
+ // setElement(1, this.elements[this.size--]);
+ // this.elements[this.size + 1] = null;
+ //
+ // if (this.size != 0) {
+ // percolateDownMinHeap(1);
+ // }
+
+ return result;
+ }
+
+ /**
+ *
+ * @param index
+ */
+ public Queueable dequeue(final int index) {
+ if ( index < 1 || index > this.size ) {
+ //throw new NoSuchElementException();
+ return null;
+ }
+
+ final Queueable result = this.elements[index];
+ setElement( index,
+ this.elements[this.size] );
+ this.elements[this.size] = null;
+ this.size--;
+ if ( this.size != 0 && index <= this.size ) {
+ int compareToParent = 0;
+ if ( index > 1 ) {
+ compareToParent = compare( this.elements[index],
+ this.elements[index / 2] );
+ }
+ if ( index > 1 && compareToParent < 0 ) {
+ percolateUpMinHeap( index );
+ } else {
+ percolateDownMinHeap( index );
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Percolates Queueable down heap from the position given by the index.
+ * <p/>
+ * Assumes it is a minimum heap.
+ *
+ * @param index the index for the Queueable
+ */
+ private void percolateDownMinHeap(final int index) {
+ final Queueable element = this.elements[index];
+ int hole = index;
+
+ while ( (hole * 2) <= this.size ) {
+ int child = hole * 2;
+
+ // if we have a right child and that child can not be percolated
+ // up then move onto other child
+ if ( child != this.size && compare( this.elements[child + 1],
+ this.elements[child] ) < 0 ) {
+ child++;
+ }
+
+ // if we found resting place of bubble then terminate search
+ if ( compare( this.elements[child],
+ element ) >= 0 ) {
+ break;
+ }
+
+ setElement( hole,
+ this.elements[child] );
+ hole = child;
+ }
+
+ setElement( hole,
+ element );
+ }
+
+ /**
+ * Percolates Queueable up heap from the position given by the index.
+ * <p/>
+ * Assumes it is a minimum heap.
+ *
+ * @param index the index of the Queueable to be percolated up
+ */
+ private void percolateUpMinHeap(final int index) {
+ int hole = index;
+ final Queueable element = this.elements[hole];
+ while ( hole > 1 && compare( element,
+ this.elements[hole / 2] ) < 0 ) {
+ // save Queueable that is being pushed down
+ // as the Queueable "bubble" is percolated up
+ final int next = hole / 2;
+ setElement( hole,
+ this.elements[next] );
+ hole = next;
+ }
+ setElement( hole,
+ element );
+ }
+
+ /**
+ * Percolates a new Queueable up heap from the bottom.
+ * <p/>
+ * Assumes it is a minimum heap.
+ *
+ * @param element the Queueable
+ */
+ private void percolateUpMinHeap(final Queueable element) {
+ setElement( ++this.size,
+ element );
+ percolateUpMinHeap( this.size );
+ }
+
+ /**
+ * Compares two objects using the comparator if specified, or the
+ * natural order otherwise.
+ *
+ * @param a the first object
+ * @param b the second object
+ * @return -ve if a less than b, 0 if they are equal, +ve if a greater than b
+ */
+ private int compare(final Queueable a,
+ final Queueable b) {
+ return this.comparator.compare( a,
+ b );
+ }
+
+ /**
+ * Increases the size of the heap to support additional elements
+ */
+ private void grow() {
+ final Queueable[] elements = new Queueable[this.elements.length * 2];
+ System.arraycopy( this.elements,
+ 0,
+ elements,
+ 0,
+ this.elements.length );
+ this.elements = elements;
+ }
+
+ /**
+ *
+ * @param index
+ * @param element
+ */
+ private void setElement(final int index,
+ final Queueable element) {
+ this.elements[index] = element;
+ element.enqueued( this,
+ index );
+ }
+
+ public Queueable[] getQueueable() {
+ return this.elements;
+ }
+
+ public Object[] toArray() {
+ final Object[] result = new Object[this.size];
+ System.arraycopy( this.elements,
+ 1,
+ result,
+ 0,
+ this.size );
+ return result;
+ }
+
+ public Object[] toArray(Object a[]) {
+ if ( a.length < this.size ) {
+ a = (Object[]) java.lang.reflect.Array.newInstance( a.getClass().getComponentType(),
+ this.size );
+ }
+
+ System.arraycopy( this.elements,
+ 1,
+ a,
+ 0,
+ this.size );
+
+ if ( a.length > this.size ) {
+ a[this.size] = null;
+ }
+
+ return a;
+ }
+}
\ No newline at end of file
Deleted: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/EmptyMapIterator.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/EmptyMapIterator.java 2006-10-12 23:46:18 UTC (rev 6773)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/EmptyMapIterator.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -1,97 +0,0 @@
-package org.drools.util;
-
-/*
- * Copyright 2005 JBoss Inc
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import java.util.NoSuchElementException;
-
-/**
- * Provides an implementation of an empty map iterator.
- *
- * @since Commons Collections 3.1
- * @version $Revision: 1.1 $ $Date: 2005/07/26 01:06:32 $
- *
- * @author Stephen Colebourne
- */
-public class EmptyMapIterator
- implements
- MapIterator {
-
- /**
- * Singleton instance of the iterator.
- *
- * @since Commons Collections 3.1
- */
- public static final MapIterator INSTANCE = new EmptyMapIterator();
-
- /**
- * Constructor.
- */
- protected EmptyMapIterator() {
- }
-
- public boolean hasNext() {
- return false;
- }
-
- public Object next() {
- throw new NoSuchElementException( "Iterator contains no elements" );
- }
-
- public boolean hasPrevious() {
- return false;
- }
-
- public Object previous() {
- throw new NoSuchElementException( "Iterator contains no elements" );
- }
-
- public int nextIndex() {
- return 0;
- }
-
- public int previousIndex() {
- return -1;
- }
-
- public void add(final Object obj) {
- throw new UnsupportedOperationException( "add() not supported for empty Iterator" );
- }
-
- public void set(final Object obj) {
- throw new IllegalStateException( "Iterator contains no elements" );
- }
-
- public void remove() {
- throw new IllegalStateException( "Iterator contains no elements" );
- }
-
- public Object getKey() {
- throw new IllegalStateException( "Iterator contains no elements" );
- }
-
- public Object getValue() {
- throw new IllegalStateException( "Iterator contains no elements" );
- }
-
- public Object setValue(final Object value) {
- throw new IllegalStateException( "Iterator contains no elements" );
- }
-
- public void reset() {
- // do nothing
- }
-}
\ No newline at end of file
Deleted: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/FastCollection.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/FastCollection.java 2006-10-12 23:46:18 UTC (rev 6773)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/FastCollection.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -1,619 +0,0 @@
-package org.drools.util;
-
-/*
- * Javolution - Java(TM) Solution for Real-Time and Embedded Systems
- * Copyright (C) 2005 - Javolution (http://javolution.org/)
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software is
- * freely granted, provided that this notice is preserved.
- */
-
-import java.io.Serializable;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Set;
-
-/**
- * <p> This class represents collections which can quickly be iterated over
- * (forward or backward) in a thread-safe manner without creating new
- * objects and without using {@link #iterator iterators} . For example:[code]
- * boolean search(Object item, FastCollection c) {
- * for (Record r = c.head(), end = c.tail(); (r = r.getNext()) != end;) {
- * if (item.equals(c.valueOf(r))) return true;
- * }
- * return false;
- * }[/code]</p>
- *
- * <p> Iterations are thread-safe as long as the {@link Record record} sequence
- * iterated over is not structurally modified by another thread
- * (objects can safely be append/prepend during iterations but not
- * inserted/removed).</p>
- *
- * <p> Users may provide a read-only view of any {@link FastCollection}
- * instance using the {@link #unmodifiable()} method (the view is
- * thread-safe if iterations are thread-safe). For example:[code]
- * public class Polynomial {
- * private final FastTable<Coefficient> _coefficients = new FastTable<Coefficient>();
- * public List<Coefficient> getCoefficients() { // Read-only view.
- * return _coefficients.unmodifiable();
- * }
- * }[/code]</p>
- *
- * <p> Finally, {@link FastCollection} may use custom {@link #setValueComparator
- * comparators} for element equality or ordering if the collection is
- * ordered (e.g. <code>FastTree</code>).
- *
- * @author <a href="mailto:jean-marie at dautelle.com">Jean-Marie Dautelle</a>
- * @version 3.6, September 24, 2005
- */
-public abstract class FastCollection
- /*<E>*/implements
- Collection/*<E>*/,
- Serializable {
-
- /**
- * Holds the value comparator.
- */
- private FastComparator _valueComp = FastComparator.DEFAULT;
-
- /**
- * Holds the unmodifiable view (allocated in the same memory area as
- * this collection).
- */
- private Unmodifiable _unmodifiable;
-
- /**
- * Default constructor.
- */
- protected FastCollection() {
- }
-
- /**
- * Returns the number of values in this collection.
- *
- * @return the number of values.
- */
- public abstract int size();
-
- /**
- * Returns the head record of this collection; it is the record such as
- * <code>head().getNext()</code> holds the first collection value.
- *
- * @return the head record.
- */
- public abstract Record head();
-
- /**
- * Returns the tail record of this collection; it is the record such as
- * <code>tail().getPrevious()</code> holds the last collection value.
- *
- * @return the tail record.
- */
- public abstract Record tail();
-
- /**
- * Returns the collection value for the specified record.
- *
- * @param record the record whose current value is returned.
- * @return the current value.
- */
- public abstract Object/*E*/valueOf(Record record);
-
- /**
- * Deletes the specified record from this collection.
- *
- * <p> Implementation must ensure that removing a record from the
- * collection does not affect in any way the records preceding
- * the record being removed (it might affect the next records though,
- * e.g. in a list collection, the indices of the subsequent records
- * will change).</p>
- *
- * @param record the record to be removed.
- * @throws UnsupportedOperationException if not supported.
- */
- public abstract void delete(Record record);
-
- /**
- * Returns the unmodifiable view associated to this collection.
- * Attempts to modify the returned collection result in an
- * {@link UnsupportedOperationException} being thrown. The view is
- * typically part of the collection itself (created only once)
- * and also an instance of {@link FastCollection} supporting direct
- * iterations.
- *
- * @return the unmodifiable view over this collection.
- */
- public Collection/*<E>*/unmodifiable() {
- if ( this._unmodifiable == null ) {
- this._unmodifiable = new Unmodifiable();
- }
- return this._unmodifiable;
- }
-
- /**
- * Returns an iterator over the elements in this collection
- * (allocated on the stack when executed in a
- * {@link javolution.realtime.PoolContext PoolContext}).
- *
- * @return an iterator over this collection's elements.
- */
- public Iterator/*<E>*/iterator() {
- return FastIterator.valueOf( this );
- }
-
- /**
- * Sets the comparator to use for value equality or ordering if the
- * collection is ordered (e.g. <code>FastTree</code>).
- *
- * @param comparator the value comparator.
- * @return <code>this</code>
- */
- public FastCollection/*<E>*/setValueComparator(final FastComparator comparator) {
- this._valueComp = comparator;
- return this;
- }
-
- /**
- * Returns the value comparator for this collection (default
- * {@link FastComparator#DEFAULT}).
- *
- * @return the comparator to use for value equality (or ordering if
- * the collection is ordered)
- */
- public FastComparator getValueComparator() {
- return this._valueComp;
- }
-
- /**
- * Appends the specified value to the end of this collection
- * (optional operation).
- *
- * <p>Note: This default implementation always throws
- * <code>UnsupportedOperationException</code>.</p>
- *
- * @param value the value to be appended to this collection.
- * @return <code>true</code> (as per the general contract of the
- * <code>Collection.add</code> method).
- * @throws UnsupportedOperationException if not supported.
- */
- public boolean add(final Object/*E*/value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Removes the first occurrence in this collection of the specified value
- * (optional operation).
- *
- * @param value the value to be removed from this collection.
- * @return <code>true</code> if this collection contained the specified
- * value; <code>false</code> otherwise.
- * @throws UnsupportedOperationException if not supported.
- */
- public boolean remove(final Object value) {
- final FastComparator valueComp = this.getValueComparator();
- for ( Record r = head(), end = tail(); (r = r.getNext()) != end; ) {
- if ( valueComp.areEqual( value,
- valueOf( r ) ) ) {
- delete( r );
- return true;
- }
- }
- return false;
- }
-
- /**
- * Removes all of the values from this collection (optional operation).
- *
- * @throws UnsupportedOperationException if not supported.
- */
- public void clear() {
- // Removes last record until empty.
- for ( Record head = head(), r = tail().getPrevious(); r != head; r = r.getPrevious() ) {
- delete( r );
- }
- }
-
- /**
- * Indicates if this collection is empty.
- *
- * @return <code>true</code> if this collection contains no value;
- * <code>false</code> otherwise.
- */
- public final boolean isEmpty() {
- return size() == 0;
- }
-
- /**
- * Indicates if this collection contains the specified value.
- *
- * @param value the value whose presence in this collection
- * is to be tested.
- * @return <code>true</code> if this collection contains the specified
- * value;<code>false</code> otherwise.
- */
- public boolean contains(final Object value) {
- final FastComparator valueComp = this.getValueComparator();
- for ( Record r = head(), end = tail(); (r = r.getNext()) != end; ) {
- if ( valueComp.areEqual( value,
- valueOf( r ) ) ) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Appends all of the values in the specified collection to the end of
- * this collection, in the order that they are returned by the specified
- * collection's iterator or the node order if the specified collection
- * is a {@link FastCollection}.
- *
- * @param c collection whose values are to be added to this collection.
- * @return <code>true</code> if this collection changed as a result of
- * the call; <code>false</code> otherwise.
- */
- public boolean addAll(final Collection/*<? extends E>*/c) {
- if ( c instanceof FastCollection ) {
- return addAll( (FastCollection) c );
- }
- boolean modified = false;
- final Iterator/*<? extends E>*/itr = c.iterator();
- int pos = c.size();
- while ( --pos >= 0 ) {
- if ( add( itr.next() ) ) {
- modified = true;
- }
- }
- return modified;
- }
-
- private boolean addAll(final FastCollection/*<? extends E>*/c) {
- boolean modified = false;
- for ( Record r = c.head(), end = c.tail(); (r = r.getNext()) != end; ) {
- if ( this.add( c.valueOf( r ) ) ) {
- modified = true;
- }
- }
- return modified;
- }
-
- /**
- * Indicates if this collection contains all of the values of the
- * specified collection.
- *
- * @param c collection to be checked for containment in this collection.
- * @return <code>true</code> if this collection contains all of the values
- * of the specified collection; <code>false</code> otherwise.
- */
- public boolean containsAll(final Collection/*<?>*/c) {
- if ( c instanceof FastCollection ) {
- return containsAll( (FastCollection) c );
- }
- final Iterator/*<?>*/itr = c.iterator();
- int pos = c.size();
- while ( --pos >= 0 ) {
- if ( !contains( itr.next() ) ) {
- return false;
- }
- }
- return true;
- }
-
- private boolean containsAll(final FastCollection/*<?>*/c) {
- for ( Record r = c.head(), end = c.tail(); (r = r.getNext()) != end; ) {
- if ( !contains( c.valueOf( r ) ) ) {
- return false;
- }
- }
- return true;
- }
-
- /**
- * Removes from this collection all the values that are contained in the
- * specified collection.
- *
- * @param c collection that defines which values will be removed from
- * this collection.
- * @return <code>true</code> if this collection changed as a result of
- * the call; <code>false</code> otherwise.
- */
- public boolean removeAll(final Collection/*<?>*/c) {
- boolean modified = false;
- // Iterates from the tail and removes the record if present in c.
- for ( Record head = head(), r = tail().getPrevious(), previous; r != head; r = previous ) {
- previous = r.getPrevious(); // Saves previous.
- if ( c.contains( valueOf( r ) ) ) {
- delete( r );
- modified = true;
- }
- }
- return modified;
- }
-
- /**
- * Retains only the values in this collection that are contained in the
- * specified collection.
- *
- * @param c collection that defines which values this set will retain.
- * @return <code>true</code> if this collection changed as a result of
- * the call; <code>false</code> otherwise.
- */
- public boolean retainAll(final Collection/*<?>*/c) {
- boolean modified = false;
- // Iterates from the tail and remove the record if not present in c.
- for ( Record head = head(), r = tail().getPrevious(), previous; r != head; r = previous ) {
- previous = r.getPrevious(); // Saves previous.
- if ( !c.contains( valueOf( r ) ) ) {
- delete( r );
- modified = true;
- }
- }
- return modified;
- }
-
- /**
- * Returns a new array allocated on the heap containing all of the values
- * in this collection in proper sequence.
- * <p> Note: To avoid heap allocation {@link #toArray(Object[])} is
- * recommended.</p>
- * @return <code>toArray(new Object[size()])</code>
- */
- public Object[] toArray() {
- return toArray( new Object[size()] );
- }
-
- /**
- * Fills the specified array with the values of this collection in
- * the proper sequence.
- *
- * <p> Note: Unlike standard Collection, this method does not try to resize
- * the array using reflection (which might not be supported) if
- * the array is too small. UnsupportedOperationException is raised
- * if the specified array is too small for this collection.</p>
- *
- * @param array the array into which the values of this collection
- * are to be stored.
- * @return the specified array.
- * @throws UnsupportedOperationException if <code>array.length < size()</code>
- */
- public Object[]/* <T> T[]*/toArray(final Object[]/*T[]*/array) {
- final int size = size();
- if ( array.length < size ) {
- throw new UnsupportedOperationException( "Destination array too small" );
- }
- if ( array.length > size ) {
- array[size] = null; // As per Collection contract.
- }
- int i = 0;
- final Object[] arrayView = array;
- for ( Record r = head(), end = tail(); (r = r.getNext()) != end; ) {
- arrayView[i++] = valueOf( r );
- }
- return array;
- }
-
- /**
- * Returns the textual representation of this collection.
- *
- * @return this collection textual representation.
- */
- public String toString() {
- final String sep = ", ";
- StringBuffer text = new StringBuffer( "[" );
- for ( Record r = head(), end = tail(); (r = r.getNext()) != end; ) {
- text = text.append( String.valueOf( r ) );
- if ( r.getNext() != end ) {
- text = text.append( sep );
- }
- }
- return text.append( ']' ).toString();
- }
-
- /**
- * Compares the specified object with this collection for equality. Returns
- * <code>true</code> if and only both collection contains the same values
- * regardless of the order; unless this collection is a list instance
- * in which case both collection must be list with the same order.
- *
- * @param obj the object to be compared for equality with this collection.
- * @return <code>true</code> if the specified object is equal to this
- * collection; <code>false</code> otherwise.
- */
- public boolean equals(final Object obj) {
- if ( this instanceof List ) {
- return equalsList( obj );
- }
- return obj == this || (obj instanceof Collection && ((Collection) obj).size() == size() && containsAll( (Collection) obj ));
- }
-
- private boolean equalsList(final Object obj) {
- final FastComparator comp = this.getValueComparator();
- if ( obj == this ) {
- return true;
- }
- if ( obj instanceof List ) {
- final List/*<?>*/list = (List) obj;
- if ( this.size() != list.size() ) {
- return false;
- }
- Record r1 = this.head();
- final Iterator/*<?>*/i2 = list.iterator();
- for ( int i = this.size(); i-- != 0; ) {
- r1 = r1.getNext();
- final Object o1 = this.valueOf( r1 );
- final Object o2 = i2.next();
- if ( !comp.areEqual( o1,
- o2 ) ) {
- return false;
- }
- }
- return true;
- }
- return false;
- }
-
- /**
- * Returns the hash code for this collection (independent from the
- * collection order; unless this collection is a list instance).
- *
- * @return the hash code for this collection.
- */
- public int hashCode() {
- if ( this instanceof List ) {
- return hashCodeList();
- }
- final FastComparator valueComp = this.getValueComparator();
- int hash = 0;
- for ( Record r = head(), end = tail(); (r = r.getNext()) != end; ) {
- hash += valueComp.hashCodeOf( valueOf( r ) );
- }
- return hash;
- }
-
- private int hashCodeList() {
- final FastComparator comp = this.getValueComparator();
- int h = 1;
- for ( Record r = head(), end = tail(); (r = r.getNext()) != end; ) {
- h = 31 * h + comp.hashCodeOf( valueOf( r ) );
- }
- return h;
-
- }
-
- /**
- * This interface represents the collection records which can directly be
- * iterated over.
- */
- public interface Record {
-
- /**
- * Returns the record before this one.
- *
- * @return the previous record.
- */
- public Record getPrevious();
-
- /**
- * Returns the record after this one.
- *
- * @return the next record.
- */
- public Record getNext();
-
- }
-
- /**
- * This inner class represents an unmodifiable view over the collection.
- */
- private final class Unmodifiable extends FastCollection
- implements
- Set,
- List { // Allows to be used for unmodifiable set/list view.
-
- /**
- *
- */
- private static final long serialVersionUID = -5929790997648211020L;
-
- // Implements abstract method.
- public int size() {
- return FastCollection.this.size();
- }
-
- // Implements abstract method.
- public Record head() {
- return FastCollection.this.head();
- }
-
- // Implements abstract method.
- public Record tail() {
- return FastCollection.this.tail();
- }
-
- // Implements abstract method.
- public Object valueOf(final Record record) {
- return FastCollection.this.valueOf( record );
- }
-
- // Forwards...
- public boolean contains(final Object value) {
- return (FastCollection.this).contains( value );
- }
-
- // Forwards...
- public boolean containsAll(final Collection c) {
- return (FastCollection.this).containsAll( c );
- }
-
- // Forwards...
- public FastComparator getValueComparator() {
- return FastCollection.this.getValueComparator();
- }
-
- // Disallows...
- public FastCollection setValueComparator(final FastComparator comparator) {
- throw new UnsupportedOperationException( "Unmodifiable" );
- }
-
- // Disallows...
- public boolean add(final Object obj) {
- throw new UnsupportedOperationException( "Unmodifiable" );
- }
-
- // Disallows...
- public void delete(final Record node) {
- throw new UnsupportedOperationException( "Unmodifiable" );
- }
-
- //////////////////////////////////////////
- // List interface supplementary methods //
- //////////////////////////////////////////
-
- public boolean addAll(final int index,
- final Collection c) {
- throw new UnsupportedOperationException( "Unmodifiable" );
- }
-
- public Object get(final int index) {
- return ((List) FastCollection.this).get( index );
- }
-
- public Object set(final int index,
- final Object element) {
- throw new UnsupportedOperationException( "Unmodifiable" );
- }
-
- public void add(final int index,
- final Object element) {
- throw new UnsupportedOperationException( "Unmodifiable" );
- }
-
- public Object remove(final int index) {
- throw new UnsupportedOperationException( "Unmodifiable" );
- }
-
- public int indexOf(final Object o) {
- return ((List) FastCollection.this).indexOf( o );
- }
-
- public int lastIndexOf(final Object o) {
- return ((List) FastCollection.this).lastIndexOf( o );
- }
-
- public ListIterator listIterator() {
- throw new UnsupportedOperationException( "List iterator not supported for unmodifiable collection" );
- }
-
- public ListIterator listIterator(final int index) {
- throw new UnsupportedOperationException( "List iterator not supported for unmodifiable collection" );
- }
-
- public List subList(final int fromIndex,
- final int toIndex) {
- throw new UnsupportedOperationException( "Sub-List not supported for unmodifiable collection" );
- }
- }
-}
Deleted: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/FastComparator.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/FastComparator.java 2006-10-12 23:46:18 UTC (rev 6773)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/FastComparator.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -1,382 +0,0 @@
-package org.drools.util;
-
-/*
- * Javolution - Java(TM) Solution for Real-Time and Embedded Systems
- * Copyright (C) 2005 - Javolution (http://javolution.org/)
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software is
- * freely granted, provided that this notice is preserved.
- */
-
-import java.io.Serializable;
-import java.util.Comparator;
-
-/**
- * <p> This class represents a comparator to be used for equality as well as
- * for ordering; instances of this class provide a hashcode function
- * consistent with equal (if two objects {@link #areEqual
- * are equal}, they have the same {@link #hashCodeOf hashcode}),
- * equality with <code>null</code> values is supported.</p>
- *
- * <p> {@link FastComparator} can be employed with {@link FastMap} (e.g. custom
- * key comparators for identity maps, value retrieval using keys of a
- * different class that the map keys) or with {@link FastCollection}
- * classes.</p>
- *
- * @author <a href="mailto:jean-marie at dautelle.com">Jean-Marie Dautelle</a>
- * @version 3.4, September 20, 2005
- */
-public abstract class FastComparator
- /*<T>*/implements
- Comparator/*<T>*/,
- Serializable {
-
- /**
- * Indicates if the system hash code should be rehashed
- * (see <a href="{@docRoot}/overview-summary.html#configuration">
- * Javolution Configuration</a> for details).
- */
- public static final boolean REHASH_SYSTEM_HASHCODE = isPoorSystemHash();
-
- /**
- * Holds the default object comparator; rehash is performed if the
- * system hash code (platform dependent) is not evenly distributed.
- * @see <a href="{@docRoot}/overview-summary.html#configuration">
- * Javolution Configuration</a>
- */
- public static final FastComparator DEFAULT = new Default( FastComparator.REHASH_SYSTEM_HASHCODE );
-
- static class Default extends FastComparator {
- /**
- *
- */
- private static final long serialVersionUID = 8861926890612437587L;
- private boolean _rehash;
-
- public Default(final boolean rehash) {
- this._rehash = rehash;
- }
-
- public int hashCodeOf(final Object obj) {
- return (this._rehash ? FastComparator.REHASH.hashCodeOf( obj ) : obj.hashCode());
- }
-
- public boolean areEqual(final Object o1,
- final Object o2) {
- return (o1 == null) ? (o2 == null) : (o1 == o2) || o1.equals( o2 );
- }
-
- public int compare(final Object o1,
- final Object o2) {
- return ((Comparable) o1).compareTo( o2 );
- }
-
- public String toString() {
- return "default";
- }
-
- };
-
- /**
- * Holds the direct object comparator; no rehash is performed.
- * Two objects o1 and o2 are considered {@link #areEqual equal} if and
- * only if <code>o1.equals(o2)</code>. The {@link #compare} method
- * throws {@link ClassCastException} if the specified objects are not
- * {@link Comparable}.
- */
- public static final FastComparator DIRECT = new Direct();
-
- static class Direct extends FastComparator {
- /**
- *
- */
- private static final long serialVersionUID = 8105021907265110872L;
-
- public int hashCodeOf(final Object obj) {
- return obj.hashCode();
- }
-
- public boolean areEqual(final Object o1,
- final Object o2) {
- return (o1 == null) ? (o2 == null) : (o1 == o2) || o1.equals( o2 );
- }
-
- public int compare(final Object o1,
- final Object o2) {
- return ((Comparable) o1).compareTo( o2 );
- }
-
- public String toString() {
- return "direct";
- }
-
- };
-
- /**
- * Holds the comparator for objects with uneven hash distribution; objects
- * hashcodes are rehashed. Two objects o1 and o2 are considered
- * {@link #areEqual equal} if and only if <code>o1.equals(o2)</code>.
- * The {@link #compare} method throws {@link ClassCastException} if the
- * specified objects are not {@link Comparable}.
- */
- public static final FastComparator REHASH = new Rehash();
-
- static class Rehash extends FastComparator {
- /**
- *
- */
- private static final long serialVersionUID = -2958722429891710908L;
-
- public int hashCodeOf(final Object obj) {
- // Formula identical <code>java.util.HashMap</code> to ensures
- // similar behavior for ill-conditioned hashcode keys.
- int h = obj.hashCode();
- h += ~(h << 9);
- h ^= (h >>> 14);
- h += (h << 4);
- return h ^ (h >>> 10);
- }
-
- public boolean areEqual(final Object o1,
- final Object o2) {
- return (o1 == null) ? (o2 == null) : (o1 == o2) || o1.equals( o2 );
- }
-
- public int compare(final Object o1,
- final Object o2) {
- return ((Comparable) o1).compareTo( o2 );
- }
-
- public String toString() {
- return "rehash";
- }
-
- };
-
- /**
- * Holds the identity comparator; poorly distributed system hashcodes are
- * rehashed. Two objects o1 and o2 are considered {@link #areEqual equal}
- * if and only if <code>(o1 == o2)</code>. The {@link #compare} method
- * throws {@link ClassCastException} if the specified objects are not
- * {@link Comparable}.
- */
- public static final FastComparator IDENTITY = new Identity();
-
- static class Identity extends FastComparator {
- /**
- *
- */
- private static final long serialVersionUID = -3868143955449541107L;
- private boolean _rehash = FastComparator.REHASH_SYSTEM_HASHCODE;
-
- public int hashCodeOf(final Object obj) {
- int h = System.identityHashCode( obj );
- if ( !this._rehash ) {
- return h;
- }
- h += ~(h << 9);
- h ^= (h >>> 14);
- h += (h << 4);
- return h ^ (h >>> 10);
-
- }
-
- public boolean areEqual(final Object o1,
- final Object o2) {
- return o1 == o2;
- }
-
- public int compare(final Object o1,
- final Object o2) {
- return ((Comparable) o1).compareTo( o2 );
- }
-
- public String toString() {
- return "identity";
- }
- };
-
- /**
- * Holds a lexicographic comparator for any {@link CharSequence} or
- * {@link String} instances.
- * Two objects are considered {@link #areEqual equal} if and only if they
- * represents the same character sequence). The hashcode is calculated
- * using the following formula (same as for <code>java.lang.String</code>):
- * <code>s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]</code>
- */
- public static final FastComparator LEXICAL = new Lexical();
-
- static class Lexical extends FastComparator {
-
- /**
- *
- */
- private static final long serialVersionUID = -6311812856053220728L;
-
- public int hashCodeOf(final Object obj) {
- if ( obj instanceof String ) {
- return obj.hashCode();
- }
- final CharSequence chars = (CharSequence) obj;
- int h = 0;
- final int length = chars.length();
- for ( int i = 0; i < length; ) {
- h = 31 * h + chars.charAt( i++ );
- }
- return h;
- }
-
- public boolean areEqual(final Object o1,
- final Object o2) {
- if ( (o1 instanceof String) && (o2 instanceof String) ) {
- return o1.equals( o2 );
- }
- if ( (o1 instanceof CharSequence) && (o2 instanceof String) ) {
- final CharSequence csq = (CharSequence) o1;
- final String str = (String) o2;
- final int length = str.length();
- if ( csq.length() != length ) {
- return false;
- }
- for ( int i = 0; i < length; ) {
- if ( str.charAt( i ) != csq.charAt( i++ ) ) {
- return false;
- }
- }
- return true;
- }
- if ( (o1 instanceof String) && (o2 instanceof CharSequence) ) {
- final CharSequence csq = (CharSequence) o2;
- final String str = (String) o1;
- final int length = str.length();
- if ( csq.length() != length ) {
- return false;
- }
- for ( int i = 0; i < length; ) {
- if ( str.charAt( i ) != csq.charAt( i++ ) ) {
- return false;
- }
- }
- return true;
- }
- final CharSequence csq1 = (CharSequence) o1;
- final CharSequence csq2 = (CharSequence) o2;
- final int length = csq1.length();
- if ( csq2.length() != length ) {
- return false;
- }
- for ( int i = 0; i < length; ) {
- if ( csq1.charAt( i ) != csq2.charAt( i++ ) ) {
- return false;
- }
- }
- return true;
- }
-
- public int compare(final Object left,
- final Object right) {
- if ( left instanceof String ) {
- if ( right instanceof String ) {
- return ((String) left).compareTo( (String) right );
- }
- // Right must be a CharSequence.
- final String seq1 = (String) left;
- final CharSequence seq2 = (CharSequence) right;
- int i = 0;
- int n = Math.min( seq1.length(),
- seq2.length() );
- while ( n-- != 0 ) {
- final char c1 = seq1.charAt( i );
- final char c2 = seq2.charAt( i++ );
- if ( c1 != c2 ) {
- return c1 - c2;
- }
- }
- return seq1.length() - seq2.length();
- }
- if ( right instanceof String ) {
- return -compare( right,
- left );
- }
-
- // Both are CharSequence.
- final CharSequence seq1 = (CharSequence) left;
- final CharSequence seq2 = (CharSequence) right;
- int i = 0;
- int n = Math.min( seq1.length(),
- seq2.length() );
- while ( n-- != 0 ) {
- final char c1 = seq1.charAt( i );
- final char c2 = seq2.charAt( i++ );
- if ( c1 != c2 ) {
- return c1 - c2;
- }
- }
- return seq1.length() - seq2.length();
- }
-
- public String toString() {
- return "lexical";
- }
-
- };
-
- /**
- * Returns the hash code for the specified object (consistent with
- * {@link #areEqual}). Two objects considered {@link #areEqual equal} have
- * the same hash code.
- *
- * @param obj the object to return the hashcode for.
- * @return the hashcode for the specified object.
- * @throws NullPointerException if the specified object is
- * <code>null</code>.
- */
- public abstract int hashCodeOf(Object/*T*/obj);
-
- /**
- * Indicates if the specified objects can be considered equal.
- *
- * @param o1 the first object (or <code>null</code>).
- * @param o2 the second object (or <code>null</code>).
- * @return <code>true</code> if both objects are considered equal;
- * <code>false</code> otherwise.
- */
- public abstract boolean areEqual(Object/*T*/o1,
- Object/*T*/o2);
-
- /**
- * Compares the specified objects for order. Returns a negative integer,
- * zero, or a positive integer as the first argument is less than, equal to,
- * or greater than the second.
- *
- * @param o1 the first object.
- * @param o2 the second object.
- * @return a negative integer, zero, or a positive integer as the first
- * argument is less than, equal to, or greater than the second.
- * @throws NullPointerException if any of the specified object is
- * <code>null</code>.
- */
- public abstract int compare(Object/*T*/o1,
- Object/*T*/o2);
-
- /**
- * Test the system hash code.
- *
- * @return <code>true</code> if the system hash code is not evenly
- * distributed; <code>false<code> otherwise.
- */
- private static boolean isPoorSystemHash() {
- final boolean[] dist = new boolean[32]; // Length power of 2.
- for ( int i = 0; i < dist.length; i++ ) {
- dist[new Object().hashCode() & (dist.length - 1)] = true;
- }
- int holes = 0;
- for ( int i = 0; i < dist.length; i++ ) {
- if ( !dist[i] ) {
- holes++; // Count holes.
- }
- }
- return holes > (dist.length >> 1);
- }
-}
\ No newline at end of file
Deleted: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/FastIterator.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/FastIterator.java 2006-10-12 23:46:18 UTC (rev 6773)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/FastIterator.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -1,73 +0,0 @@
-package org.drools.util;
-
-/*
- * Javolution - Java(TM) Solution for Real-Time and Embedded Systems
- * Copyright (C) 2005 - Javolution (http://javolution.org/)
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software is
- * freely granted, provided that this notice is preserved.
- */
-
-import java.util.Iterator;
-import java.util.NoSuchElementException;
-
-import org.drools.util.FastCollection.Record;
-
-/**
- * <p> This class represents an iterator over a {@link Fastcollection).
- * Iterations are thread-safe if the collections records are not removed
- * or inserted at arbitrary position (appending/prepending is fine).</p>
- *
- * @author <a href="mailto:jean-marie at dautelle.com">Jean-Marie Dautelle</a>
- * @version 3.7, March 17, 2005
- */
-final class FastIterator
- implements
- Iterator {
-
- private FastCollection _collection;
-
- private Record _current;
-
- private Record _next;
-
- private Record _tail;
-
- public static FastIterator valueOf(final FastCollection collection) {
- final FastIterator iterator = new FastIterator();
- iterator._collection = collection;
- iterator._next = collection.head().getNext();
- iterator._tail = collection.tail();
- return iterator;
- }
-
- private FastIterator() {
- }
-
- public boolean hasNext() {
- return (this._next != this._tail);
- }
-
- public Object next() {
- if ( this._next == this._tail ) {
- throw new NoSuchElementException();
- }
- this._current = this._next;
- this._next = this._next.getNext();
- return this._collection.valueOf( this._current );
- }
-
- public void remove() {
- if ( this._current != null ) {
- // Uses the previous record (not affected by the remove)
- // to set the next record.
- final Record previous = this._current.getPrevious();
- this._collection.delete( this._current );
- this._current = null;
- this._next = previous.getNext();
- } else {
- throw new IllegalStateException();
- }
- }
-}
\ No newline at end of file
Deleted: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/FastMap.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/FastMap.java 2006-10-12 23:46:18 UTC (rev 6773)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/FastMap.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -1,1310 +0,0 @@
-package org.drools.util;
-
-/*
- * Javolution - Java(TM) Solution for Real-Time and Embedded Systems
- * Copyright (C) 2005 - Javolution (http://javolution.org/)
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software is
- * freely granted, provided that this notice is preserved.
- */
-
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.PrintStream;
-import java.io.Serializable;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * <p> This class represents a hash map with real-time behavior;
- * smooth capacity increase and no rehashing ever performed.</p>
- * <img src="doc-files/map-put.png"/>
- *
- * <p> {@link FastMap} has a predictable iteration order, which is the order in
- * which keys are inserted into the map (similar to
- * <code>java.util.LinkedHashMap</code> collection class).</p>
- *
- * <p> {@link FastMap.Entry} can quickly be iterated over (forward or backward)
- * without using iterators. For example:[code]
- * FastMap<String, Thread> map = new FastMap<String, Thread>();
- * for (FastMap.Entry<String, Thread> e = map.head(), end = map.tail(); (e = e.getNext()) != end;) {
- * String key = e.getKey(); // No typecast necessary.
- * Thread value = e.getValue(); // No typecast necessary.
- * }[/code]</p>
- *
- * <p> {@link FastMap} may use custom key comparators; the default comparator is
- * either {@link FastComparator#DIRECT DIRECT} or
- * {@link FastComparator#REHASH REHASH} based upon the current <a href=
- * "{@docRoot}/overview-summary.html#configuration">Javolution
- * Configuration</a>. Users may explicitly set the key comparator to
- * {@link FastComparator#DIRECT DIRECT} for optimum performance
- * when the hash codes are well distributed for all run-time platforms
- * (e.g. calculated hash codes).</p>
- *
- * <p> Custom key comparators are extremely useful for value retrieval when
- * map's keys and argument keys are not of the same class, such as
- * {@link String} and {@link javolution.lang.Text Text}
- * ({@link FastComparator#LEXICAL LEXICAL}) or for identity maps
- * ({@link FastComparator#IDENTITY IDENTITY}).
- * For example:[code]
- * FastMap identityMap = new FastMap().setKeyComparator(FastComparator.IDENTITY);
- * [/code]</p>
- *
- * <p> {@link FastMap} marked {@link #setShared(boolean) shared} are
- * thread-safe without external synchronization and are often good
- * substitutes for <code>ConcurrentHashMap</code>. For example:[code]
- * // Holds the units multiplication lookup table (persistent).
- * static final FastMap<Unit, FastMap<Unit, Unit>> MULT_LOOKUP
- * = new FastMap<Unit, FastMap<Unit, Unit>>("mult-unit-lookup").setShared(true);
- *
- * // Fast and non-blocking (no synchronization necessary).
- * static Unit productOf(Unit left, Unit right) {
- * FastMap<Unit, Unit> leftTable = MULT_LOOKUP.get(left);
- * if (leftTable == null) return calculateProductOf(left, right);
- * Unit result = leftTable.get(right);
- * if (result == null) return calculateProductOf(left, right);
- * return result; // Returns cache result.
- * }[/code]</p>
- *
- * <p> Finally, {@link FastMap} are {@link Reusable reusable}; they maintain an
- * internal pool of <code>Map.Entry</code> objects. When an entry is removed
- * from a map, it is automatically restored to its pool (unless the map
- * is shared in which case the removed entry is candidate for garbage
- * collection as it cannot be safely recycled).</p>
- *
- * @author <a href="mailto:jean-marie at dautelle.com">Jean-Marie Dautelle </a>
- * @version 3.7, March 29, 2006
- */
-public class FastMap
- /*<K,V>*/implements
- Map/*<K,V>*/,
- Serializable {
-
- /**
- *
- */
- private static final long serialVersionUID = -4281546938715716829L;
-
- /**
- * Holds table higher index rotation.
- */
- private static final int R0 = 5;
-
- /**
- * Holds the table lower index mask.
- */
- private static final int M0 = (1 << FastMap.R0) - 1;
-
- /**
- * Holds the map's hash table.
- * Use two dimensional arrays to avoid large arrays allocations.
- */
- private transient Entry/*<K,V>*/[][] _entries;
-
- /**
- * Holds the head entry to which the first entry attaches.
- * The head entry never changes (entries always added last).
- */
- private transient Entry /*<K,V>*/_head = new Entry();
-
- /**
- * Holds the tail entry to which the last entry attaches.
- * The tail entry changes as entries are added/removed.
- */
- private transient Entry /*<K,V>*/_tail = new Entry();
-
- /**
- * Holds the current size.
- */
- private transient int _size;
-
- /**
- * Holds the values view.
- */
- private transient Values _values = new Values();
-
- /**
- * Holds the key set view.
- */
- private transient KeySet _keySet = new KeySet();
-
- /**
- * Holds the entry set view.
- */
- private transient EntrySet _entrySet = new EntrySet();
-
- /**
- * Holds the unmodifiable view.
- */
- private transient Map /*<K,V>*/_unmodifiable = new Unmodifiable();
-
- /**
- * Holds a reference to a map having the old entries when resizing.
- */
- private transient FastMap /*<K,V>*/_oldEntries;
-
- /**
- * Holds the key comparator.
- */
- private transient FastComparator _keyComparator = FastComparator.DEFAULT;
-
- /**
- * Holds comparator set to <code>null</code> when equivalent to direct.
- */
- private transient FastComparator _keyComp = FastComparator.REHASH_SYSTEM_HASHCODE ? FastComparator.REHASH : null;
-
- /**
- * Indicates if this map is shared (thread-safe).
- */
- private transient boolean _isShared;
-
- /**
- * Creates a fast map of small initial capacity.
- */
- public FastMap() {
- this( 4 );
- }
-
- /**
- * Creates a map of specified initial capacity; unless the map size
- * reaches the specified capacity, operations on this map will not allocate
- * memory (no lazy object creation).
- *
- * @param capacity the initial capacity.
- */
- public FastMap(final int capacity) {
- int tableLength = 1 << FastMap.R0;
- while ( tableLength < capacity ) {
- tableLength <<= 1;
- }
- this._entries = new Entry[tableLength >> FastMap.R0][];
- for ( int i = 0; i < this._entries.length; ) {
- this._entries[i++] = new Entry[1 << FastMap.R0];
- }
- this._head._next = this._tail;
- this._tail._previous = this._head;
- Entry/*<K,V>*/previous = this._tail;
- for ( int i = 0; i++ < capacity; ) {
- final Entry/*<K,V>*/newEntry = new Entry/*<K,V>*/();
- newEntry._previous = previous;
- previous._next = newEntry;
- previous = newEntry;
- }
- }
-
- /**
- * Creates a map containing the specified entries, in the order they
- * are returned by the map iterator.
- *
- * @param map the map whose entries are to be placed into this map.
- */
- public FastMap(final Map/*<? extends K, ? extends V>*/map) {
- this( map.size() );
- putAll( map );
- }
-
- /**
- * Creates a fast map having the specified entry table.
- *
- * @param entries the entry table.
- */
- private FastMap(final Entry/*<K,V>*/[][] entries) {
- this._entries = entries;
- this._head._next = this._tail;
- this._tail._previous = this._head;
- }
-
- /**
- * Returns the head entry of this map.
- *
- * @return the entry such as <code>head().getNext()</code> holds
- * the first map entry.
- */
- public final Entry/*<K,V>*/head() {
- return this._head;
- }
-
- /**
- * Returns the tail entry of this map.
- *
- * @return the entry such as <code>tail().getPrevious()</code>
- * holds the last map entry.
- */
- public final Entry/*<K,V>*/tail() {
- return this._tail;
- }
-
- /**
- * Returns the number of key-value mappings in this {@link FastMap}.
- *
- * @return this map's size.
- */
- public final int size() {
- return this._size;
- }
-
- /**
- * Indicates if this map contains no key-value mappings.
- *
- * @return <code>true</code> if this map contains no key-value mappings;
- * <code>false</code> otherwise.
- */
- public final boolean isEmpty() {
- return this._head._next == this._tail;
- }
-
- /**
- * Indicates if this map contains a mapping for the specified key.
- *
- * @param key the key whose presence in this map is to be tested.
- * @return <code>true</code> if this map contains a mapping for the
- * specified key; <code>false</code> otherwise.
- * @throws NullPointerException if the key is <code>null</code>.
- */
- public final boolean containsKey(final Object key) {
- return getEntry( key ) != null;
- }
-
- /**
- * Indicates if this map associates one or more keys to the specified value.
- *
- * @param value the value whose presence in this map is to be tested.
- * @return <code>true</code> if this map maps one or more keys to the
- * specified value.
- * @throws NullPointerException if the key is <code>null</code>.
- */
- public final boolean containsValue(final Object value) {
- return this._values.contains( value );
- }
-
- /**
- * Returns the value to which this map associates the specified key.
- *
- * @param key the key whose associated value is to be returned.
- * @return the value to which this map maps the specified key, or
- * <code>null</code> if there is no mapping for the key.
- * @throws NullPointerException if key is <code>null</code>.
- */
- public final Object/*V*/get(final Object key) {
- final Entry/*<K,V>*/entry = getEntry( key,
- (this._keyComp == null) ? key.hashCode() : this._keyComp.hashCodeOf( key ) );
- return (entry != null) ? entry._value : null;
- }
-
- /**
- * Returns the entry with the specified key.
- *
- * @param key the key whose associated entry is to be returned.
- * @return the entry for the specified key or <code>null</code> if none.
- */
- public final Entry/*<K,V>*/getEntry(final Object key) {
- return getEntry( key,
- (this._keyComp == null) ? key.hashCode() : this._keyComp.hashCodeOf( key ) );
- }
-
- /**
- * Associates the specified value with the specified key in this map.
- * If this map previously contained a mapping for this key, the old value
- * is replaced. For {@link #isShared() shared} map internal synchronization
- * is automatically performed.
- *
- * @param key the key with which the specified value is to be associated.
- * @param value the value to be associated with the specified key.
- * @return the previous value associated with specified key, or
- * <code>null</code> if there was no mapping for key. A
- * <code>null</code> return can also indicate that the map
- * previously associated <code>null</code> with the specified key.
- * @throws NullPointerException if the key is <code>null</code>.
- */
- public final Object/*V*/put(final Object/*K*/key,
- final Object/*V*/value) {
- final int keyHash = (this._keyComp == null) ? key.hashCode() : this._keyComp.hashCodeOf( key );
- if ( this._isShared ) {
- return putShared( key,
- value,
- keyHash );
- }
- final Entry/*<K,V>*/entry = getEntry( key,
- keyHash );
- if ( entry == null ) {
- addEntry( keyHash,
- key,
- value );
- return null;
- }
- final Object/*V*/prevValue = entry._value;
- entry._value = value;
- return prevValue;
- }
-
- private synchronized Object/*V*/putShared(final Object/*K*/key,
- final Object/*V*/value,
- final int keyHash) {
- final Entry/*<K,V>*/entry = getEntry( key,
- keyHash );
- if ( entry == null ) {
- addEntry( keyHash,
- key,
- value );
- return null;
- }
- final Object/*V*/prevValue = entry._value;
- entry._value = value;
- return prevValue;
- }
-
- /**
- * Copies all of the mappings from the specified map to this map.
- *
- * @param map the mappings to be stored in this map.
- * @throws NullPointerException the specified map is <code>null</code>,
- * or the specified map contains <code>null</code> keys.
- */
- public final void putAll(final Map/*<? extends K, ? extends V>*/map) {
- if ( map instanceof FastMap ) { // Optimization.
- final FastMap/*<? extends K, ? extends V>*/fm = (FastMap/*<? extends K, ? extends V>*/) map;
- for ( Entry/*<? extends K, ? extends V>*/e = fm._head, end = fm._tail; (e = e._next) != end; ) {
- put( e._key,
- e._value );
- }
- } else {
- for ( final Iterator i = map.entrySet().iterator(); i.hasNext(); ) {
- final Map.Entry/*<? extends K, ? extends V>*/e = (Map.Entry/*<? extends K, ? extends V>*/) i.next();
- put( e.getKey(),
- e.getValue() );
- }
- }
- }
-
- /**
- * Removes the entry for the specified key if present. The entry
- * is recycled if the map is not marked as {@link #isShared shared};
- * otherwise the entry is candidate for garbage collection.
- *
- * <p> Note: Shared maps in ImmortalMemory (e.g. static) should not remove
- * their entries as it could cause a memory leak (ImmortalMemory
- * is never garbage collected), instead they should set their
- * entry values to <code>null</code>.</p>
- *
- * @param key the key whose mapping is to be removed from the map.
- * @return previous value associated with specified key, or
- * <code>null</code> if there was no mapping for key. A
- * <code>null</code> return can also indicate that the map
- * previously associated <code>null</code> with the specified key.
- * @throws NullPointerException if the key is <code>null</code>.
- */
- public final Object/*V*/remove(final Object key) {
- if ( this._isShared ) {
- return removeShared( key );
- }
- final Entry/*<K,V>*/entry = getEntry( key );
- if ( entry != null ) {
- final Object/*V*/prevValue = entry._value;
- removeEntry( entry );
- return prevValue;
- }
- return null;
- }
-
- private synchronized Object/*V*/removeShared(final Object key) {
- final Entry/*<K,V>*/entry = getEntry( key );
- if ( entry != null ) {
- this._size--;
- entry.detach();
- return entry._value;
- }
- return null;
- }
-
- /**
- * <p> Sets the shared status of this map (whether the map is thread-safe
- * or not). Shared maps are typically used for lookup table (e.g. static
- * instances in ImmortalMemory). They support concurrent access
- * (e.g. iterations) without synchronization, the maps updates
- * themselves are synchronized internally.</p>
- * <p> Unlike <code>ConcurrentHashMap</code> access to a shared map never
- * blocks. Retrieval reflects the map state not older than the last
- * time the accessing thread has been synchronized (for multi-processors
- * systems synchronizing ensures that the CPU internal cache is not
- * stale).</p>
- *
- * @param isShared <code>true</code> if this map is shared and thread-safe;
- * <code>false</code> otherwise.
- * @return <code>this</code>
- */
- public FastMap/*<K,V>*/setShared(final boolean isShared) {
- this._isShared = isShared;
- return this;
- }
-
- /**
- * Indicates if this map supports concurrent operations without
- * synchronization (default unshared).
- *
- * @return <code>true</code> if this map is thread-safe; <code>false</code>
- * otherwise.
- */
- public boolean isShared() {
- return this._isShared;
- }
-
- /**
- * Sets the key comparator for this fast map.
- *
- * @param keyComparator the key comparator.
- * @return <code>this</code>
- */
- public FastMap/*<K,V>*/setKeyComparator(final FastComparator keyComparator) {
- this._keyComparator = keyComparator;
- this._keyComp = (keyComparator instanceof FastComparator.Default) ? (FastComparator.REHASH_SYSTEM_HASHCODE ? FastComparator.REHASH : null) : (keyComparator instanceof FastComparator.Direct) ? null : keyComparator;
- return this;
- }
-
- /**
- * Returns the key comparator for this fast map.
- *
- * @return the key comparator.
- */
- public FastComparator getKeyComparator() {
- return this._keyComparator;
- }
-
- /**
- * Sets the value comparator for this map.
- *
- * @param valueComparator the value comparator.
- * @return <code>this</code>
- */
- public FastMap/*<K,V>*/setValueComparator(final FastComparator valueComparator) {
- this._values.setValueComparator( valueComparator );
- return this;
- }
-
- /**
- * Returns the value comparator for this fast map.
- *
- * @return the value comparator.
- */
- public FastComparator getValueComparator() {
- return this._values.getValueComparator();
- }
-
- /**
- * Removes all map's entries. The entries are removed and recycled;
- * unless this map is {@link #isShared shared} in which case the entries
- * are candidate for garbage collection.
- *
- * <p> Note: Shared maps in ImmortalMemory (e.g. static) should not remove
- * their entries as it could cause a memory leak (ImmortalMemory
- * is never garbage collected), instead they should set their
- * entry values to <code>null</code>.</p>
- */
- public final void clear() {
- if ( this._isShared ) {
- clearShared();
- return;
- }
- // Clears all keys, values and buckets linked lists.
- for ( Entry/*<K,V>*/e = this._head, end = this._tail; (e = e._next) != end; ) {
- e._key = null;
- e._value = null;
- final Entry/*<K,V>*/[][] table = e._table;
- table[(e._keyHash >> FastMap.R0) & (table.length - 1)][e._keyHash & FastMap.M0] = null;
- }
- this._tail = this._head._next;
- this._size = 0;
-
- // Discards old entries.
- this._oldEntries = null;
- }
-
- private synchronized void clearShared() {
- for ( Entry/*<K,V>*/e = this._head, end = this._tail; (e = e._next) != end; ) {
- final Entry/*<K,V>*/[][] table = e._table;
- table[(e._keyHash >> FastMap.R0) & (table.length - 1)][e._keyHash & FastMap.M0] = null;
- }
- this._head._next = this._tail; // Does not modify current linked list.
- this._tail._previous = this._head; //
- this._oldEntries = null;
- this._size = 0;
- }
-
- /**
- * Compares the specified object with this map for equality.
- * Returns <code>true</code> if the given object is also a map and the two
- * maps represent the same mappings (regardless of collection iteration
- * order).
- *
- * @param obj the object to be compared for equality with this map.
- * @return <code>true</code> if the specified object is equal to this map;
- * <code>false</code> otherwise.
- */
- public boolean equals(final Object obj) {
- if ( obj == this ) {
- return true;
- } else if ( obj instanceof Map ) {
- final Map/*<?,?>*/that = (Map) obj;
- if ( this.size() == that.size() ) {
- final Set thatEntrySet = that.entrySet();
- for ( Entry e = this._head, end = this._tail; (e = e._next) != end; ) {
- if ( !thatEntrySet.contains( e ) ) {
- return false;
- }
- }
- return true;
- } else {
- return false;
- }
- } else {
- return false;
- }
- }
-
- /**
- * Returns the hash code value for this map.
- *
- * @return the hash code value for this map.
- */
- public int hashCode() {
- int code = 0;
- for ( Entry e = this._head, end = this._tail; (e = e._next) != end; ) {
- code += e.hashCode();
- }
- return code;
- }
-
- /**
- * Returns the textual representation of this map.
- *
- * @return the textual representation of the entry set.
- */
- public String toString() {
- return this._entrySet.toString();
- }
-
- /**
- * Prints the current statistics on this map.
- * This method may help identify poorly defined hash functions.
- * An average collision of less than <code>50%</code> is typically
- * acceptable.
- *
- * @param out the stream to use for output (e.g. <code>System.out</code>)
- */
- public void printStatistics(final PrintStream out) {
- int maxOccupancy = 0;
- int totalCollisions = 0;
- int size = 0;
- for ( int i = 0; i < this._entries.length; i++ ) {
- for ( int j = 0; j < this._entries[i].length; j++ ) {
- Entry entry = this._entries[i][j];
- int occupancy = 0;
- while ( entry != null ) {
- occupancy++;
- if ( occupancy > maxOccupancy ) {
- maxOccupancy = occupancy;
- }
- if ( occupancy > 1 ) {
- totalCollisions++;
- }
- entry = entry._beside;
- size++;
- }
- }
- }
- final StringBuffer percentCollisions = new StringBuffer();
- if ( size != 0 ) {
- percentCollisions.append( (100 * totalCollisions) / size );
- percentCollisions.append( '%' );
- } else {
- percentCollisions.append( "N/A" );
- }
- synchronized ( out ) {
- out.print( "SIZE: " + size );
- out.print( ", TABLE LENGTH: " + this._entries.length * this._entries[0].length );
- out.print( ", AVG COLLISIONS: " + percentCollisions );
- out.print( ", MAX SLOT OCCUPANCY: " + maxOccupancy );
- out.print( ", KEY COMPARATOR: " + ((this._keyComp == null) ? FastComparator.DIRECT : this._keyComp) );
- out.print( ", SHARED: " + this._isShared );
- out.println();
- if ( this._oldEntries != null ) {
- out.print( " + " );
- this._oldEntries.printStatistics( out );
- }
- }
- }
-
- /**
- * Returns a {@link FastCollection} view of the values contained in this
- * map. The collection is backed by the map, so changes to the
- * map are reflected in the collection, and vice-versa. The collection
- * supports element removal, which removes the corresponding mapping from
- * this map, via the <code>Iterator.remove</code>,
- * <code>Collection.remove</code>, <code>removeAll</code>,
- * <code>retainAll</code> and <code>clear</code> operations.
- * It does not support the <code>add</code> or <code>addAll</code>
- * operations.
- *
- * @return a collection view of the values contained in this map
- * (instance of {@link FastCollection}).
- */
- public final Collection/*<V>*/values() {
- return this._values;
- }
-
- private final class Values extends FastCollection {
-
- /**
- *
- */
- private static final long serialVersionUID = 8804295702684770940L;
-
- public int size() {
- return FastMap.this._size;
- }
-
- public void clear() {
- FastMap.this.clear();
- }
-
- public Record head() {
- return FastMap.this._head;
- }
-
- public Record tail() {
- return FastMap.this._tail;
- }
-
- public Object valueOf(final Record record) {
- return ((Entry) record)._value;
- }
-
- public void delete(final Record record) {
- FastMap.this.remove( ((Entry) record).getKey() );
- }
- }
-
- /**
- * Returns a {@link FastCollection} view of the mappings contained in this
- * map. Each element in the returned collection is a
- * <code>FastMap.Entry</code>. The collection is backed by the map, so
- * changes to the map are reflected in the collection, and vice-versa. The
- * collection supports element removal, which removes the corresponding
- * mapping from this map, via the <code>Iterator.remove</code>,
- * <code>Collection.remove</code>,<code>removeAll</code>,
- * <code>retainAll</code>, and <code>clear</code> operations. It does
- * not support the <code>add</code> or <code>addAll</code> operations.
- *
- * @return a collection view of the mappings contained in this map
- * (instance of {@link FastCollection}).
- */
- public final Set/*<Map.Entry<K,V>>*/entrySet() {
- return this._entrySet;
- }
-
- private final class EntrySet extends FastCollection
- implements
- Set {
-
- /**
- *
- */
- private static final long serialVersionUID = 8729117163337735415L;
-
- public int size() {
- return FastMap.this._size;
- }
-
- public void clear() {
- FastMap.this.clear();
- }
-
- public boolean contains(final Object obj) { // Optimization.
- if ( obj instanceof Map.Entry ) {
- final Map.Entry entry = (Entry) obj;
- final Entry mapEntry = getEntry( entry.getKey() );
- return entry.equals( mapEntry );
- } else {
- return false;
- }
- }
-
- public String toString() {
- StringBuffer text = new StringBuffer( "[" );
- final String equ = "=";
- final String sep = ", ";
- for ( Entry e = FastMap.this._head, end = FastMap.this._tail; (e = e._next) != end; ) {
- text = text.append( String.valueOf( e._key ) ).append( equ ).append( String.valueOf( e._value ) );
- if ( e._next != end ) {
- text = text.append( sep );
- }
- }
- return text.append( ']' ).toString();
- }
-
- public Record head() {
- return FastMap.this._head;
- }
-
- public Record tail() {
- return FastMap.this._tail;
- }
-
- public Object valueOf(final Record record) {
- return record;
- }
-
- public void delete(final Record record) {
- FastMap.this.remove( ((Entry) record).getKey() );
- }
- }
-
- /**
- * Returns a {@link FastCollection} view of the keys contained in this
- * map. The set is backed by the map, so changes to the map are reflected
- * in the set, and vice-versa. The set supports element removal, which
- * removes the corresponding mapping from this map, via the
- * <code>Iterator.remove</code>, <code>Collection.remove</code>,<code>removeAll<f/code>,
- * <code>retainAll</code>, and <code>clear</code> operations. It does
- * not support the <code>add</code> or <code>addAll</code> operations.
- *
- * @return a set view of the keys contained in this map
- * (instance of {@link FastCollection}).
- */
- public final Set/*<K>*/keySet() {
- return this._keySet;
- }
-
- private final class KeySet extends FastCollection
- implements
- Set {
-
- /**
- *
- */
- private static final long serialVersionUID = -2629453921452583782L;
-
- public int size() {
- return FastMap.this._size;
- }
-
- public void clear() {
- FastMap.this.clear();
- }
-
- public boolean contains(final Object obj) { // Optimization.
- return FastMap.this.containsKey( obj );
- }
-
- public boolean remove(final Object obj) { // Optimization.
- return FastMap.this.remove( obj ) != null;
- }
-
- public Record head() {
- return FastMap.this._head;
- }
-
- public Record tail() {
- return FastMap.this._tail;
- }
-
- public Object valueOf(final Record record) {
- return ((Entry) record)._key;
- }
-
- public void delete(final Record record) {
- FastMap.this.remove( ((Entry) record).getKey() );
- }
- }
-
- /**
- * Returns the unmodifiable view associated to this map.
- * Attempts to modify the returned map or to directly access its
- * (modifiable) map entries (e.g. <code>unmodifiable().entrySet()</code>)
- * result in an {@link UnsupportedOperationException} being thrown.
- * Unmodifiable {@link FastCollection} views of this map keys and values
- * are nonetheless obtainable (e.g. <code>unmodifiable().keySet(),
- * <code>unmodifiable().values()</code>).
- *
- * @return an unmodifiable view of this map.
- */
- public final Map/*<K,V>*/unmodifiable() {
- return this._unmodifiable;
- }
-
- /**
- * Returns the entry with the specified key and hash code.
- *
- * @param key the key whose associated entry is to be returned.
- * @param the associated hash code (need to be calculated only once).
- * @return the entry for the specified key or <code>null</code> if none.
- */
- private final Entry/*<K,V>*/getEntry(final Object key,
- final int keyHash) {
- Entry/*<K,V>*/entry = this._entries[(keyHash >> FastMap.R0) & (this._entries.length - 1)][keyHash & FastMap.M0];
- while ( entry != null ) {
- if ( (key == entry._key) || ((entry._keyHash == keyHash) && ((this._keyComp == null) ? key.equals( entry._key ) : this._keyComp.areEqual( key,
- entry._key ))) ) {
- return entry;
- }
- entry = entry._beside;
- }
- return (this._oldEntries != null) ? this._oldEntries.getEntry( key,
- keyHash ) : null;
- }
-
- /**
- * Adds a new entry for the specified key and value.
- *
- * @param hash the hash of the key, generated with {@link #keyHash}.
- * @param key the entry's key.
- * @param value the entry's value.
- */
- private void addEntry(final int hash,
- final Object/*K*/key,
- final Object/*V*/value) {
- // Updates size.
- if ( (this._size++ >> FastMap.R0) >= this._entries.length ) { // Check if entry table too small.
- increaseEntryTable();
- }
-
- if ( this._tail._next == null ) {
- increaseCapacity();
- }
- final Entry newTail = this._tail._next;
- // Setups entry parameters.
- this._tail._key = key;
- this._tail._value = value;
- this._tail._keyHash = hash;
- this._tail._table = this._entries;
-
- // Connects to bucket.
- final int index = (hash >> FastMap.R0) & (this._entries.length - 1);
- Entry[] tmp = this._entries[index];
- if ( tmp == FastMap.NULL_BLOCK ) {
- newBlock( index );
- tmp = this._entries[index];
- }
- final Entry beside = tmp[hash & FastMap.M0];
- this._tail._beside = beside;
- tmp[hash & FastMap.M0] = this._tail;
-
- // Moves tail forward.
- this._tail = newTail;
- }
-
- /**
- * Removes the specified entry from the specified map.
- * The entry is added to the internal pool.
- *
- * @param entry the entry to be removed.
- * @param the map from which the entry is removed.
- */
- private final void removeEntry(final Entry entry) {
-
- // Updates size.
- this._size--;
-
- // Clears value and key.
- entry._key = null;
- entry._value = null;
-
- // Detaches from list and bucket.
- entry.detach();
-
- // Re-inserts next tail.
- final Entry next = this._tail._next;
- entry._previous = this._tail;
- entry._next = next;
- this._tail._next = entry;
- if ( next != null ) {
- next._previous = entry;
- }
- }
-
- // Allocates a new block.
- private void newBlock(final int index) {
- this._entries[index] = new Entry[1 << FastMap.R0];
- }
-
- // Increases capacity (_tail._next == null)
- private void increaseCapacity() {
- final Entry/*<K,V>*/newEntry0 = new Entry/*<K,V>*/();
- this._tail._next = newEntry0;
- newEntry0._previous = this._tail;
-
- final Entry/*<K,V>*/newEntry1 = new Entry/*<K,V>*/();
- newEntry0._next = newEntry1;
- newEntry1._previous = newEntry0;
-
- final Entry/*<K,V>*/newEntry2 = new Entry/*<K,V>*/();
- newEntry1._next = newEntry2;
- newEntry2._previous = newEntry1;
-
- final Entry/*<K,V>*/newEntry3 = new Entry/*<K,V>*/();
- newEntry2._next = newEntry3;
- newEntry3._previous = newEntry2;
-
- }
-
- // Increases the table size, the table length is multiplied by 8.
- // It still ensures that no more half memory space is unused
- // (most space is being taken by the entries objects themselves).
- private void increaseEntryTable() {
- final int newLength = this._entries.length << 3;
- FastMap/*<K,V>*/tmp;
- if ( newLength <= (1 << 3) ) { //
- tmp = new FastMap/*<K,V>*/( new Entry[1 << 3][] ); // 256
- } else if ( newLength <= (1 << 6) ) {
- tmp = new FastMap/*<K,V>*/( new Entry[1 << 6][] ); // 2048
- } else if ( newLength <= (1 << 9) ) {
- tmp = new FastMap/*<K,V>*/( new Entry[1 << 9][] ); // 16,384
- } else if ( newLength <= (1 << 12) ) {
- tmp = new FastMap/*<K,V>*/( new Entry[1 << 12][] ); // 131,072
- } else if ( newLength <= (1 << 15) ) {
- tmp = new FastMap/*<K,V>*/( new Entry[1 << 15][] ); // 1,048,576
- } else if ( newLength <= (1 << 18) ) {
- tmp = new FastMap/*<K,V>*/( new Entry[1 << 18][] );
- } else if ( newLength <= (1 << 21) ) {
- tmp = new FastMap/*<K,V>*/( new Entry[1 << 21][] );
- } else if ( newLength <= (1 << 24) ) {
- tmp = new FastMap/*<K,V>*/( new Entry[1 << 24][] );
- } else if ( newLength <= (1 << 27) ) {
- tmp = new FastMap/*<K,V>*/( new Entry[1 << 27][] );
- } else { // Cannot increase.
- return;
- }
- for ( int i = 0; i < tmp._entries.length; ) {
- tmp._entries[i++] = FastMap.NULL_BLOCK;
- }
-
- // Takes the entry from the new map.
- final Entry[][] newEntries = tmp._entries;
-
- // Setups what is going to be the old entries.
- tmp._entries = this._entries;
- tmp._oldEntries = this._oldEntries;
- tmp._keyComp = this._keyComp;
- tmp._head = null;
- tmp._tail = null;
- tmp._size = -1;
-
- // Swaps entries.
- this._oldEntries = tmp;
- checkpoint(); // Both this and _oldEntries have the same entries.
- this._entries = newEntries; // Use new larger entry table now.
-
- // Done. We have now a much larger entry table.
- // Still, we keep reference to the old entries through oldEntries
- // until the map is cleared.
-
- }
-
- private static final Entry[] NULL_BLOCK = new Entry[1 << FastMap.R0];
-
- // Implements Reusable.
- public void reset() {
- setShared( false ); // A shared map can only be reset if no thread use it.
- clear(); // In which case, it is safe to recycle the entries.
- setKeyComparator( FastComparator.DEFAULT );
- setValueComparator( FastComparator.DEFAULT );
- }
-
- /**
- * Requires special handling during de-serialization process.
- *
- * @param stream the object input stream.
- * @throws IOException if an I/O error occurs.
- * @throws ClassNotFoundException if the class for the object de-serialized
- * is not found.
- */
- private void readObject(final ObjectInputStream stream) throws IOException,
- ClassNotFoundException {
- final int size = stream.readInt();
- final int entriesLength = stream.readInt();
-
- // Initializes transient fields.
- this._entries = new FastMap.Entry[entriesLength][];
- for ( int i = 0; i < this._entries.length; ) {
- this._entries[i++] = FastMap.NULL_BLOCK;
- }
- this._head = new Entry();
- this._tail = new Entry();
- this._head._next = this._tail;
- this._tail._previous = this._head;
- this._values = new Values();
- this._entrySet = new EntrySet();
- this._keySet = new KeySet();
- this._unmodifiable = new Unmodifiable();
-
- setShared( stream.readBoolean() );
- setKeyComparator( (FastComparator) stream.readObject() );
- setValueComparator( (FastComparator) stream.readObject() );
-
- // Reads data.
- for ( int i = 0; i < size; i++ ) {
- final Object/*K*/key = stream.readObject();
- final Object/*V*/value = stream.readObject();
- addEntry( this._keyComparator.hashCodeOf( key ),
- key,
- value );
- }
- }
-
- /**
- * Requires special handling during serialization process.
- *
- * @param stream the object output stream.
- * @throws IOException if an I/O error occurs.
- */
- private void writeObject(final ObjectOutputStream stream) throws IOException {
- stream.writeInt( this._size );
- stream.writeInt( this._entries.length );
-
- stream.writeBoolean( this._isShared );
- stream.writeObject( this._keyComparator );
- stream.writeObject( this._values.getValueComparator() );
-
- for ( Entry e = this._head, end = this._tail; (e = e._next) != end; ) {
- stream.writeObject( e._key );
- stream.writeObject( e._value );
- }
- }
-
- /**
- * This class represents a {@link FastMap} entry.
- */
- public static final class Entry
- /*<K,V>*/implements
- Map.Entry/*<K,V>*/,
- FastCollection.Record {
-
- /**
- * Holds the next node.
- */
- private Entry /*<K,V>*/_next;
-
- /**
- * Holds the previous node.
- */
- private Entry /*<K,V>*/_previous;
-
- /**
- * Holds the entry key.
- */
- private Object /*K*/_key;
-
- /**
- * Holds the entry value.
- */
- private Object /*V*/_value;
-
- /**
- * Holds the next entry in the same bucket.
- */
- private Entry /*<K,V>*/_beside;
-
- /**
- * Holds the hash table this entry belongs to.
- */
- private Entry/*<K,V>*/[][] _table;
-
- /**
- * Holds the key hash code.
- */
- private int _keyHash;
-
- /**
- * Default constructor.
- */
- private Entry() {
- }
-
- /**
- * Returns the entry after this one.
- *
- * @return the next entry.
- */
- public final FastCollection.Record/*Entry<K,V>*/getNext() {
- return this._next;
- }
-
- /**
- * Returns the entry before this one.
- *
- * @return the previous entry.
- */
- public final FastCollection.Record/*Entry<K,V>*/getPrevious() {
- return this._previous;
- }
-
- /**
- * Returns the key for this entry.
- *
- * @return the entry key.
- */
- public final Object/*K*/getKey() {
- return this._key;
- }
-
- /**
- * Returns the value for this entry.
- *
- * @return the entry value.
- */
- public final Object/*V*/getValue() {
- return this._value;
- }
-
- /**
- * Sets the value for this entry.
- *
- * @param value the new value.
- * @return the previous value.
- */
- public final Object/*V*/setValue(final Object/*V*/value) {
- final Object/*V*/old = this._value;
- this._value = value;
- return old;
- }
-
- /**
- * Indicates if this entry is considered equals to the specified entry
- * (using default value and key equality comparator to ensure symetry).
- *
- * @param that the object to test for equality.
- * @return <code>true<code> if both entry have equal keys and values.
- * <code>false<code> otherwise.
- */
- public boolean equals(final Object that) {
- if ( that instanceof Map.Entry ) {
- final Map.Entry entry = (Map.Entry) that;
- return this._key.equals( entry.getKey() ) && ((this._value != null) ? this._value.equals( entry.getValue() ) : (entry.getValue() == null));
- } else {
- return false;
- }
- }
-
- /**
- * Returns the hash code for this entry.
- *
- * @return this entry hash code.
- */
- public int hashCode() {
- return this._key.hashCode() ^ ((this._value != null) ? this._value.hashCode() : 0);
- }
-
- /**
- * Detaches this entry from the entry table and list.
- */
- private final void detach() {
- // Removes from list.
- this._previous._next = this._next;
- this._next._previous = this._previous;
-
- // Removes from bucket.
- final int index = (this._keyHash >> FastMap.R0) & (this._table.length - 1);
- final Entry/*<K,V>*/beside = this._beside;
- Entry/*<K,V>*/previous = this._table[index][this._keyHash & FastMap.M0];
- if ( previous == this ) { // First in bucket.
- this._table[index][this._keyHash & FastMap.M0] = beside;
- } else {
- while ( previous._beside != this ) {
- previous = previous._beside;
- }
- previous._beside = beside;
- }
- }
- }
-
- /**
- * This class represents an read-only view over a {@link FastMap}.
- */
- private final class Unmodifiable
- implements
- Map,
- Serializable {
-
- /**
- *
- */
- private static final long serialVersionUID = 2699246906507262549L;
-
- public boolean equals(final Object obj) {
- return FastMap.this.equals( obj );
- }
-
- public int hashCode() {
- return FastMap.this.hashCode();
- }
-
- public String toString() {
- return FastMap.this.toString();
- }
-
- public int size() {
- return FastMap.this.size();
- }
-
- public boolean isEmpty() {
- return FastMap.this.isEmpty();
- }
-
- public boolean containsKey(final Object key) {
- return FastMap.this.containsKey( key );
- }
-
- public boolean containsValue(final Object value) {
- return FastMap.this.containsValue( value );
- }
-
- public Object get(final Object key) {
- return FastMap.this.get( key );
- }
-
- public Object put(final Object key,
- final Object value) {
- throw new UnsupportedOperationException( "Unmodifiable map" );
- }
-
- public Object remove(final Object key) {
- throw new UnsupportedOperationException( "Unmodifiable map" );
- }
-
- public void putAll(final Map map) {
- throw new UnsupportedOperationException( "Unmodifiable map" );
- }
-
- public void clear() {
- throw new UnsupportedOperationException( "Unmodifiable map" );
- }
-
- public Set keySet() {
- return (Set) FastMap.this._keySet.unmodifiable();
- }
-
- public Collection values() {
- return FastMap.this._values.unmodifiable();
- }
-
- public Set entrySet() {
- throw new UnsupportedOperationException( "Direct view over unmodifiable map entries is not supported " + " (to prevent access to Entry.setValue(Object) method). " + "To iterate over unmodifiable map entries, applications may "
- + "use the keySet() and values() fast collection views " + "in conjonction." );
- }
- }
-
- /**
- * Ensures that the compiler will not reorder previous instructions below
- * this point.
- */
- private static void checkpoint() {
- if ( FastMap.CHECK_POINT ) {
- throw new Error(); // Reads volatile.
- }
- }
-
- static volatile boolean CHECK_POINT;
-}
\ No newline at end of file
Deleted: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/IdentityMap.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/IdentityMap.java 2006-10-12 23:46:18 UTC (rev 6773)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/IdentityMap.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -1,222 +0,0 @@
-package org.drools.util;
-
-/*
- * Copyright 2005 JBoss Inc
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-import java.util.Map;
-
-/**
- * A <code>Map</code> implementation that matches keys and values based on
- * <code>==</code> not <code>equals()</code>.
- * <p>
- * This map will violate the detail of various Map and map view contracts. As a
- * general rule, don't compare this map to other maps.
- *
- * @since Commons Collections 3.0
- * @version $Revision: 1.1 $ $Date: 2005/07/26 01:06:32 $
- *
- * @author java util HashMap
- * @author Stephen Colebourne
- */
-public class IdentityMap extends AbstractHashedMap
- implements
- Serializable,
- Cloneable {
-
- /** Serialisation version */
- private static final long serialVersionUID = 2028493495224302329L;
-
- /**
- * Constructs a new empty map with default size and load factor.
- */
- public IdentityMap() {
- super( AbstractHashedMap.DEFAULT_CAPACITY,
- AbstractHashedMap.DEFAULT_LOAD_FACTOR,
- AbstractHashedMap.DEFAULT_THRESHOLD );
- }
-
- /**
- * Constructs a new, empty map with the specified initial capacity.
- *
- * @param initialCapacity
- * the initial capacity
- * @throws IllegalArgumentException
- * if the initial capacity is less than one
- */
- public IdentityMap(final int initialCapacity) {
- super( initialCapacity );
- }
-
- /**
- * Constructs a new, empty map with the specified initial capacity and load
- * factor.
- *
- * @param initialCapacity
- * the initial capacity
- * @param loadFactor
- * the load factor
- * @throws IllegalArgumentException
- * if the initial capacity is less than one
- * @throws IllegalArgumentException
- * if the load factor is less than zero
- */
- public IdentityMap(final int initialCapacity,
- final float loadFactor) {
- super( initialCapacity,
- loadFactor );
- }
-
- /**
- * Constructor copying elements from another map.
- *
- * @param map
- * the map to copy
- * @throws NullPointerException
- * if the map is null
- */
- public IdentityMap(final Map map) {
- super( map );
- }
-
- // -----------------------------------------------------------------------
- /**
- * Gets the hash code for the key specified. This implementation uses the
- * identity hash code.
- *
- * @param key
- * the key to get a hash code for
- * @return the hash code
- */
- protected int hash(final Object key) {
- return System.identityHashCode( key );
- }
-
- /**
- * Compares two keys for equals. This implementation uses <code>==</code>.
- *
- * @param key1
- * the first key to compare
- * @param key2
- * the second key to compare
- * @return true if equal by identity
- */
- protected boolean isEqualKey(final Object key1,
- final Object key2) {
- return (key1 == key2);
- }
-
- /**
- * Compares two values for equals. This implementation uses <code>==</code>.
- *
- * @param value1
- * the first value to compare
- * @param value2
- * the second value to compare
- * @return true if equal by identity
- */
- protected boolean isEqualValue(final Object value1,
- final Object value2) {
- return (value1 == value2);
- }
-
- /**
- * Creates an entry to store the data. This implementation creates an
- * IdentityEntry instance.
- *
- * @param next
- * the next entry in sequence
- * @param hashCode
- * the hash code to use
- * @param key
- * the key to store
- * @param value
- * the value to store
- * @return the newly created entry
- */
- protected HashEntry createEntry(final HashEntry next,
- final int hashCode,
- final Object key,
- final Object value) {
- return new IdentityEntry( next,
- hashCode,
- key,
- value );
- }
-
- // -----------------------------------------------------------------------
- /**
- * HashEntry
- */
- protected static class IdentityEntry extends HashEntry {
-
- protected IdentityEntry(final HashEntry next,
- final int hashCode,
- final Object key,
- final Object value) {
- super( next,
- hashCode,
- key,
- value );
- }
-
- public boolean equals(final Object obj) {
- if ( obj == this ) {
- return true;
- }
- if ( obj instanceof Map.Entry == false ) {
- return false;
- }
- final Map.Entry other = (Map.Entry) obj;
- return (getKey() == other.getKey()) && (getValue() == other.getValue());
- }
-
- public int hashCode() {
- return System.identityHashCode( getKey() ) ^ System.identityHashCode( getValue() );
- }
- }
-
- // -----------------------------------------------------------------------
- /**
- * Clones the map without cloning the keys or values.
- *
- * @return a shallow clone
- */
- public Object clone() {
- return super.clone();
- }
-
- /**
- * Write the map out using a custom routine.
- */
- private void writeObject(final ObjectOutputStream out) throws IOException {
- out.defaultWriteObject();
- doWriteObject( out );
- }
-
- /**
- * Read the map in using a custom routine.
- */
- private void readObject(final ObjectInputStream in) throws IOException,
- ClassNotFoundException {
- in.defaultReadObject();
- doReadObject( in );
- }
-
-}
\ No newline at end of file
Deleted: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/MapIterator.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/MapIterator.java 2006-10-12 23:46:18 UTC (rev 6773)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/MapIterator.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -1,124 +0,0 @@
-package org.drools.util;
-
-/*
- * Copyright 2005 JBoss Inc
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import java.util.Iterator;
-
-/**
- * Defines an iterator that operates over a <code>Map</code>.
- * <p>
- * This iterator is a special version designed for maps. It can be more
- * efficient to use this rather than an entry set iterator where the option is
- * available, and it is certainly more convenient.
- * <p>
- * A map that provides this interface may not hold the data internally using Map
- * Entry objects, thus this interface can avoid lots of object creation.
- * <p>
- * In use, this iterator iterates through the keys in the map. After each call
- * to <code>next()</code>, the <code>getValue()</code> method provides
- * direct access to the value. The value can also be set using
- * <code>setValue()</code>.
- *
- * <pre>
- * MapIterator it = map.mapIterator();
- * while ( it.hasNext() ) {
- * Object key = it.next();
- * Object value = it.getValue();
- * it.setValue( newValue );
- * }
- * </pre>
- *
- * @since Commons Collections 3.0
- * @version $Revision: 1.1 $ $Date: 2005/07/26 01:06:32 $
- *
- * @author Stephen Colebourne
- */
-public interface MapIterator
- extends
- Iterator {
-
- /**
- * Checks to see if there are more entries still to be iterated.
- *
- * @return <code>true</code> if the iterator has more elements
- */
- boolean hasNext();
-
- /**
- * Gets the next <em>key</em> from the <code>Map</code>.
- *
- * @return the next key in the iteration
- * @throws java.util.NoSuchElementException
- * if the iteration is finished
- */
- Object next();
-
- // -----------------------------------------------------------------------
- /**
- * Gets the current key, which is the key returned by the last call to
- * <code>next()</code>.
- *
- * @return the current key
- * @throws IllegalStateException
- * if <code>next()</code> has not yet been called
- */
- Object getKey();
-
- /**
- * Gets the current value, which is the value associated with the last key
- * returned by <code>next()</code>.
- *
- * @return the current value
- * @throws IllegalStateException
- * if <code>next()</code> has not yet been called
- */
- Object getValue();
-
- // -----------------------------------------------------------------------
- /**
- * Removes the last returned key from the underlying <code>Map</code>
- * (optional operation).
- * <p>
- * This method can be called once per call to <code>next()</code>.
- *
- * @throws UnsupportedOperationException
- * if remove is not supported by the map
- * @throws IllegalStateException
- * if <code>next()</code> has not yet been called
- * @throws IllegalStateException
- * if <code>remove()</code> has already been called since the
- * last call to <code>next()</code>
- */
- void remove();
-
- /**
- * Sets the value associated with the current key (optional operation).
- *
- * @param value
- * the new value
- * @return the previous value
- * @throws UnsupportedOperationException
- * if setValue is not supported by the map
- * @throws IllegalStateException
- * if <code>next()</code> has not yet been called
- * @throws IllegalStateException
- * if <code>remove()</code> has been called since the last
- * call to <code>next()</code>
- */
- Object setValue(Object value);
-
-}
\ No newline at end of file
Deleted: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/MultiLinkedList.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/MultiLinkedList.java 2006-10-12 23:46:18 UTC (rev 6773)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/MultiLinkedList.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -1,60 +0,0 @@
-/*
- * Copyright 2005 JBoss Inc
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.drools.util;
-
-/**
- * MultiLinkedList
- * A linked list where each node has a reference to the list itself and to a
- * child node.
- *
- * @author <a href="mailto:tirelli at post.com">Edson Tirelli</a>
- *
- * Created: 14/02/2006
- */
-public class MultiLinkedList extends LinkedList {
-
- public MultiLinkedList() {
- }
-
- /**
- * Add a <code>MultiLinkedListNode</code> to the list.
- * If the <code>MultiLinkedList</code> is empty then the first and
- * last nodes are set to the added node.
- *
- * @param node
- * The <code>LinkedListNode</code> to be added
- */
- public void add(final MultiLinkedListNode node) {
- super.add( node );
- node.setOuterList( this );
- }
-
- /**
- * Removes a <code>MultiLinkedListNode</code> from the list.
- * This works by attach the previous reference to the child reference.
- * When the node to be removed is the first node it calls <code>removeFirst()</code>.
- * When the node to be removed is the last node
- * it calls <code>removeLast()</code>.
- *
- * @param node
- * The <code>LinkedListNode</code> to be removed.
- */
- public void remove(final MultiLinkedListNode node) {
- super.remove( node );
- node.setOuterList( null );
- }
-}
Deleted: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/MultiLinkedListNode.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/MultiLinkedListNode.java 2006-10-12 23:46:18 UTC (rev 6773)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/MultiLinkedListNode.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -1,61 +0,0 @@
-/*
- * Copyright 2005 JBoss Inc
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.drools.util;
-
-/**
- * MultiLinkedListNode
- * This is a specialization of the LinkedListNode that also keeps reference to
- * a child node (that might me member of another LinkedList) and the containing
- * LinkedList.
- *
- * @author <a href="mailto:tirelli at post.com">Edson Tirelli</a>
- *
- * Created: 12/02/2006
- */
-public interface MultiLinkedListNode
- extends
- LinkedListNode {
-
- /**
- * Returns the child node
- * @return
- * The child LinkedListNode
- */
- public MultiLinkedListNode getChild();
-
- /**
- * Sets the child node
- * @param child
- * The child LinkedListNode
- */
- public void setChild(MultiLinkedListNode child);
-
- /**
- * Returns the containing LinkedList
- * @return
- * The containing LinkedList
- */
- public LinkedList getOuterList();
-
- /**
- * Sets the containing LinkedList
- * @param list
- * The containing LinkedListNode
- */
- public void setOuterList(LinkedList list);
-
-}
Deleted: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/MultiLinkedListNodeWrapper.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/MultiLinkedListNodeWrapper.java 2006-10-12 23:46:18 UTC (rev 6773)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/MultiLinkedListNodeWrapper.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -1,53 +0,0 @@
-/*
- * Copyright 2005 JBoss Inc
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.drools.util;
-
-/**
- * MultiLinkedListNodeWrapper
- * A wrapper to a MultiLinkedListNode in a way you can add it to
- * another linked list without losing the references to the original
- * list.
- *
- * @author <a href="mailto:tirelli at post.com">Edson Tirelli</a>
- *
- * Created: 12/02/2006
- */
-public class MultiLinkedListNodeWrapper extends BaseMultiLinkedListNode {
-
- private static final long serialVersionUID = 3326764563267697646L;
-
- private LinkedListNode node = null;
-
- private MultiLinkedListNode parent = null;
-
- public MultiLinkedListNodeWrapper(final LinkedListNode node) {
- this.node = node;
- }
-
- public MultiLinkedListNode getParent() {
- return this.parent;
- }
-
- public void setParent(MultiLinkedListNode parent) {
- this.parent = parent;
- }
-
- public LinkedListNode getNode() {
- return this.node;
- }
-
-}
Deleted: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/PriorityQueue.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/PriorityQueue.java 2006-10-12 23:46:18 UTC (rev 6773)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/PriorityQueue.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -1,587 +0,0 @@
-package org.drools.util;
-
-/*
- * Copyright 2005 JBoss Inc
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import java.io.Serializable;
-import java.util.AbstractCollection;
-import java.util.Comparator;
-import java.util.Iterator;
-import java.util.NoSuchElementException;
-
-/**
- * Binary heap implementation of <code>Buffer</code> that provides for removal
- * based on <code>Comparator</code> ordering. <p/>The removal order of a
- * binary heap is based on either the natural sort order of its elements or a
- * specified {@linkComparator}. The {@link #remove()}method always returns the
- * first element as determined by the sort order. (The
- * <code>ascendingOrder</code> flag in the constructors can be used to reverse
- * the sort order, in which case {@link#remove()}will always remove the last
- * element.) The removal order is <i>not </i> the same as the order of
- * iteration; elements are returned by the iterator in no particular order. <p/>
- * The {@link #add(Object)}and {@link #remove()}operations perform in
- * logarithmic time. The {@link #get()}operation performs in constant time. All
- * other operations perform in linear time or worse. <p/>Note that this
- * implementation is not synchronized.
- *
- * @author Peter Donald
- * @author Ram Chidambaram
- * @author Michael A. Smith
- * @author Paul Jack
- * @author Stephen Colebourne
- * @author <a href="mailto:simon at redhillconsulting.com.au">Simon Harris </a>
- * @version $Revision: 1.1 $ $Date: 2005/07/26 01:06:32 $
- */
-public class PriorityQueue extends AbstractCollection
- implements
- Serializable {
-
- /**
- *
- */
- private static final long serialVersionUID = 640473968693160007L;
-
- /**
- * The default capacity for the buffer.
- */
- private static final int DEFAULT_CAPACITY = 13;
-
- /**
- * The elements in this buffer.
- */
- protected Object[] elements;
-
- /**
- * The number of elements currently in this buffer.
- */
- protected int size;
-
- /**
- * If true, the first element as determined by the sort order will be
- * returned. If false, the last element as determined by the sort order will
- * be returned.
- */
- protected boolean ascendingOrder;
-
- /**
- * The comparator used to order the elements
- */
- protected Comparator comparator;
-
- // -----------------------------------------------------------------------
- /**
- * Constructs a new empty buffer that sorts in ascending order by the
- * natural order of the objects added.
- */
- public PriorityQueue() {
- this( PriorityQueue.DEFAULT_CAPACITY,
- true,
- null );
- }
-
- /**
- * Constructs a new empty buffer that sorts in ascending order using the
- * specified comparator.
- *
- * @param comparator
- * the comparator used to order the elements, null means use
- * natural order
- */
- public PriorityQueue(final Comparator comparator) {
- this( PriorityQueue.DEFAULT_CAPACITY,
- true,
- comparator );
- }
-
- /**
- * Constructs a new empty buffer specifying the sort order and using the
- * natural order of the objects added.
- *
- * @param ascendingOrder
- * if <code>true</code> the heap is created as a minimum heap;
- * otherwise, the heap is created as a maximum heap
- */
- public PriorityQueue(final boolean ascendingOrder) {
- this( PriorityQueue.DEFAULT_CAPACITY,
- ascendingOrder,
- null );
- }
-
- /**
- * Constructs a new empty buffer specifying the sort order and comparator.
- *
- * @param ascendingOrder
- * true to use the order imposed by the given comparator; false
- * to reverse that order
- * @param comparator
- * the comparator used to order the elements, null means use
- * natural order
- */
- public PriorityQueue(final boolean ascendingOrder,
- final Comparator comparator) {
- this( PriorityQueue.DEFAULT_CAPACITY,
- ascendingOrder,
- comparator );
- }
-
- /**
- * Constructs a new empty buffer that sorts in ascending order by the
- * natural order of the objects added, specifying an initial capacity.
- *
- * @param capacity
- * the initial capacity for the buffer, greater than zero
- * @throws IllegalArgumentException
- * if <code>capacity</code> is <= <code>0</code>
- */
- public PriorityQueue(final int capacity) {
- this( capacity,
- true,
- null );
- }
-
- /**
- * Constructs a new empty buffer that sorts in ascending order using the
- * specified comparator and initial capacity.
- *
- * @param capacity
- * the initial capacity for the buffer, greater than zero
- * @param comparator
- * the comparator used to order the elements, null means use
- * natural order
- * @throws IllegalArgumentException
- * if <code>capacity</code> is <= <code>0</code>
- */
- public PriorityQueue(final int capacity,
- final Comparator comparator) {
- this( capacity,
- true,
- comparator );
- }
-
- /**
- * Constructs a new empty buffer that specifying initial capacity and sort
- * order, using the natural order of the objects added.
- *
- * @param capacity
- * the initial capacity for the buffer, greater than zero
- * @param ascendingOrder
- * if <code>true</code> the heap is created as a minimum heap;
- * otherwise, the heap is created as a maximum heap.
- * @throws IllegalArgumentException
- * if <code>capacity</code> is <code><= 0</code>
- */
- public PriorityQueue(final int capacity,
- final boolean ascendingOrder) {
- this( capacity,
- ascendingOrder,
- null );
- }
-
- /**
- * Constructs a new empty buffer that specifying initial capacity, sort
- * order and comparator.
- *
- * @param capacity
- * the initial capacity for the buffer, greater than zero
- * @param ascendingOrder
- * true to use the order imposed by the given comparator; false
- * to reverse that order
- * @param comparator
- * the comparator used to order the elements, null means use
- * natural order
- * @throws IllegalArgumentException
- * if <code>capacity</code> is <code><= 0</code>
- */
- public PriorityQueue(final int capacity,
- final boolean ascendingOrder,
- final Comparator comparator) {
- super();
- if ( capacity <= 0 ) {
- throw new IllegalArgumentException( "invalid capacity" );
- }
- this.ascendingOrder = ascendingOrder;
-
- // +1 as 0 is noop
- this.elements = new Object[capacity + 1];
- this.comparator = comparator;
- }
-
- // -----------------------------------------------------------------------
- /**
- * Checks whether the heap is ascending or descending order.
- *
- * @return true if ascending order (a min heap)
- */
- public boolean isAscendingOrder() {
- return this.ascendingOrder;
- }
-
- /**
- * Gets the comparator being used for this buffer, null is natural order.
- *
- * @return the comparator in use, null is natural order
- */
- public Comparator comparator() {
- return this.comparator;
- }
-
- // -----------------------------------------------------------------------
- /**
- * Returns the number of elements in this buffer.
- *
- * @return the number of elements in this buffer
- */
- public int size() {
- return this.size;
- }
-
- /**
- * Clears all elements from the buffer.
- */
- public void clear() {
- this.elements = new Object[this.elements.length]; // for gc
- this.size = 0;
- }
-
- /**
- * Adds an element to the buffer. <p/>The element added will be sorted
- * according to the comparator in use.
- *
- * @param element
- * the element to be added
- * @return true always
- */
- public boolean add(final Object element) {
- if ( isAtCapacity() ) {
- grow();
- }
- // percolate element to it's place in tree
- if ( this.ascendingOrder ) {
- percolateUpMinHeap( element );
- } else {
- percolateUpMaxHeap( element );
- }
- return true;
- }
-
- /**
- * Gets the next element to be removed without actually removing it (peek).
- *
- * @return the next element
- * @throws NoSuchElementException
- * if the buffer is empty
- */
- public Object get() {
- if ( isEmpty() ) {
- throw new NoSuchElementException();
- } else {
- return this.elements[1];
- }
- }
-
- /**
- * Gets and removes the next element (pop).
- *
- * @return the next element
- * @throws NoSuchElementException
- * if the buffer is empty
- */
- public Object remove() {
- final Object result = get();
- this.elements[1] = this.elements[this.size--];
-
- // set the unused element to 'null' so that the garbage collector
- // can free the object if not used anywhere else.(remove reference)
- this.elements[this.size + 1] = null;
-
- if ( this.size != 0 ) {
- // percolate top element to it's place in tree
- if ( this.ascendingOrder ) {
- percolateDownMinHeap( 1 );
- } else {
- percolateDownMaxHeap( 1 );
- }
- }
-
- return result;
- }
-
- // -----------------------------------------------------------------------
- /**
- * Tests if the buffer is at capacity.
- *
- * @return <code>true</code> if buffer is full; <code>false</code>
- * otherwise.
- */
- protected boolean isAtCapacity() {
- // +1 as element 0 is noop
- return this.elements.length == this.size + 1;
- }
-
- /**
- * Percolates element down heap from the position given by the index. <p/>
- * Assumes it is a minimum heap.
- *
- * @param index
- * the index for the element
- */
- protected void percolateDownMinHeap(final int index) {
- final Object element = this.elements[index];
- int hole = index;
-
- while ( (hole * 2) <= this.size ) {
- int child = hole * 2;
-
- // if we have a right child and that child can not be percolated
- // up then move onto other child
- if ( child != this.size && compare( this.elements[child + 1],
- this.elements[child] ) < 0 ) {
- child++;
- }
-
- // if we found resting place of bubble then terminate search
- if ( compare( this.elements[child],
- element ) >= 0 ) {
- break;
- }
-
- this.elements[hole] = this.elements[child];
- hole = child;
- }
-
- this.elements[hole] = element;
- }
-
- /**
- * Percolates element down heap from the position given by the index. <p/>
- * Assumes it is a maximum heap.
- *
- * @param index
- * the index of the element
- */
- protected void percolateDownMaxHeap(final int index) {
- final Object element = this.elements[index];
- int hole = index;
-
- while ( (hole * 2) <= this.size ) {
- int child = hole * 2;
-
- // if we have a right child and that child can not be percolated
- // up then move onto other child
- if ( child != this.size && compare( this.elements[child + 1],
- this.elements[child] ) > 0 ) {
- child++;
- }
-
- // if we found resting place of bubble then terminate search
- if ( compare( this.elements[child],
- element ) <= 0 ) {
- break;
- }
-
- this.elements[hole] = this.elements[child];
- hole = child;
- }
-
- this.elements[hole] = element;
- }
-
- /**
- * Percolates element up heap from the position given by the index. <p/>
- * Assumes it is a minimum heap.
- *
- * @param index
- * the index of the element to be percolated up
- */
- protected void percolateUpMinHeap(final int index) {
- int hole = index;
- final Object element = this.elements[hole];
- while ( hole > 1 && compare( element,
- this.elements[hole / 2] ) < 0 ) {
- // save element that is being pushed down
- // as the element "bubble" is percolated up
- final int next = hole / 2;
- this.elements[hole] = this.elements[next];
- hole = next;
- }
- this.elements[hole] = element;
- }
-
- /**
- * Percolates a new element up heap from the bottom. <p/>Assumes it is a
- * minimum heap.
- *
- * @param element
- * the element
- */
- protected void percolateUpMinHeap(final Object element) {
- this.elements[++this.size] = element;
- percolateUpMinHeap( this.size );
- }
-
- /**
- * Percolates element up heap from from the position given by the index.
- * <p/>Assume it is a maximum heap.
- *
- * @param index
- * the index of the element to be percolated up
- */
- protected void percolateUpMaxHeap(final int index) {
- int hole = index;
- final Object element = this.elements[hole];
-
- while ( hole > 1 && compare( element,
- this.elements[hole / 2] ) > 0 ) {
- // save element that is being pushed down
- // as the element "bubble" is percolated up
- final int next = hole / 2;
- this.elements[hole] = this.elements[next];
- hole = next;
- }
-
- this.elements[hole] = element;
- }
-
- /**
- * Percolates a new element up heap from the bottom. <p/>Assume it is a
- * maximum heap.
- *
- * @param element
- * the element
- */
- protected void percolateUpMaxHeap(final Object element) {
- this.elements[++this.size] = element;
- percolateUpMaxHeap( this.size );
- }
-
- /**
- * Compares two objects using the comparator if specified, or the natural
- * order otherwise.
- *
- * @param a
- * the first object
- * @param b
- * the second object
- * @return -ve if a less than b, 0 if they are equal, +ve if a greater than
- * b
- */
- protected int compare(final Object a,
- final Object b) {
- if ( this.comparator != null ) {
- return this.comparator.compare( a,
- b );
- } else {
- return ((Comparable) a).compareTo( b );
- }
- }
-
- /**
- * Increases the size of the heap to support additional elements
- */
- protected void grow() {
- final Object[] array = new Object[this.elements.length * 2];
- System.arraycopy( this.elements,
- 0,
- array,
- 0,
- this.elements.length );
- this.elements = array;
- }
-
- // -----------------------------------------------------------------------
- /**
- * Returns an iterator over this heap's elements.
- *
- * @return an iterator over this heap's elements
- */
- public Iterator iterator() {
- return new Iterator() {
-
- private int index = 1;
-
- private int lastReturnedIndex = -1;
-
- public boolean hasNext() {
- return this.index <= PriorityQueue.this.size;
- }
-
- public Object next() {
- if ( !hasNext() ) {
- throw new NoSuchElementException();
- }
- this.lastReturnedIndex = this.index;
- this.index++;
- return PriorityQueue.this.elements[this.lastReturnedIndex];
- }
-
- public void remove() {
- if ( this.lastReturnedIndex == -1 ) {
- throw new IllegalStateException();
- }
- PriorityQueue.this.elements[this.lastReturnedIndex] = PriorityQueue.this.elements[PriorityQueue.this.size];
- PriorityQueue.this.elements[PriorityQueue.this.size] = null;
- PriorityQueue.this.size--;
- if ( PriorityQueue.this.size != 0 && this.lastReturnedIndex <= PriorityQueue.this.size ) {
- int compareToParent = 0;
- if ( this.lastReturnedIndex > 1 ) {
- compareToParent = compare( PriorityQueue.this.elements[this.lastReturnedIndex],
- PriorityQueue.this.elements[this.lastReturnedIndex / 2] );
- }
- if ( PriorityQueue.this.ascendingOrder ) {
- if ( this.lastReturnedIndex > 1 && compareToParent < 0 ) {
- percolateUpMinHeap( this.lastReturnedIndex );
- } else {
- percolateDownMinHeap( this.lastReturnedIndex );
- }
- } else { // max heap
- if ( this.lastReturnedIndex > 1 && compareToParent > 0 ) {
- percolateUpMaxHeap( this.lastReturnedIndex );
- } else {
- percolateDownMaxHeap( this.lastReturnedIndex );
- }
- }
- }
- this.index--;
- this.lastReturnedIndex = -1;
- }
-
- };
- }
-
- /**
- * Returns a string representation of this heap. The returned string is
- * similar to those produced by standard JDK collections.
- *
- * @return a string representation of this heap
- */
- public String toString() {
- final StringBuffer sb = new StringBuffer();
-
- sb.append( "[ " );
-
- for ( int i = 1; i < this.size + 1; i++ ) {
- if ( i != 1 ) {
- sb.append( ", " );
- }
- sb.append( this.elements[i] );
- }
-
- sb.append( " ]" );
-
- return sb.toString();
- }
-
-}
\ No newline at end of file
Deleted: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/TupleEntry.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/TupleEntry.java 2006-10-12 23:46:18 UTC (rev 6773)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/TupleEntry.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -1,29 +0,0 @@
-/**
- *
- */
-package org.drools.util;
-
-import org.drools.common.InternalFactHandle;
-
-public class TupleEntry extends BaseEntry {
- private InternalFactHandle handle;
-
- public TupleEntry(InternalFactHandle handle) {
- this.handle = handle;
- }
-
- public String toString() {
- return this.handle.getObject().toString();
- }
-
- public int hashCode() {
- return this.handle.hashCode();
- }
-
- public boolean equals(Object object) {
- // Inside the rete network we know that it will always be a TupleEntry
- // We know it will never be null
- TupleEntry other = (TupleEntry) object;
- return (this.handle.getId() == other.handle.getId());
- }
-}
\ No newline at end of file
Modified: labs/jbossrules/trunk/drools-core/src/test/java/org/drools/util/BinaryHeapPriorityQueueTest.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/test/java/org/drools/util/BinaryHeapPriorityQueueTest.java 2006-10-12 23:46:18 UTC (rev 6773)
+++ labs/jbossrules/trunk/drools-core/src/test/java/org/drools/util/BinaryHeapPriorityQueueTest.java 2006-10-13 00:12:16 UTC (rev 6774)
@@ -30,7 +30,7 @@
final Random random = new Random();
final List items = new LinkedList();
- final Queue queue = new BinaryHeapFifoQueue( NaturalComparator.INSTANCE,
+ final Queue queue = new BinaryHeapQueue( NaturalComparator.INSTANCE,
100000 );
for ( int i = 0; i < 100000; ++i ) {
More information about the jboss-svn-commits
mailing list