Makefile.am: Add HashSet.java and java/lang/ref classes.
* Makefile.am: Add HashSet.java and java/lang/ref classes. Remove BasicMapEntry.java and Bucket.java. * Makefile.in: Rebuilt. * java/util/HashMap.java: Rewritten. * java/util/HashSet.java: Imported from classpath. * java/util/WeakHashMap.java: Imported from classpath. * java/util/Hashtable.java: Rewritten based on new HashMap code. * java/util/Bucket.java: Deleted. * java/util/BasicMapEntry.java: Deleted. * java/util/Collections.java (search): Use a for-loop, not iterator hasNext(). (copy): Use a for-loop. Throw an IndexOutOfBoundsException if run out of elements in source. (max): Use a for-loop. (min): Ditto. (reverse): Keep track of positions instead of using Iterator's nextIndex() and previousIndex(). (shuffle(List)): Initialize defaultRandom if required using double-check thread safety idiom. Call two-argument shuffle method using defaultRandom. (defaultRandom): New field. (shuffle(List, Random)): Use a for-loop. Keep track of pos instead of using previousIndex() and nextIndex(). (singletonMap(iterator)): Use a HashMap.Entry, not BasicMapEntry. * java/util/AbstractCollection.java (toString): Use a StringBuffer. * java/util/AbstractMap.java (toString): Use StringBuffer. * java/lang/ref/PhantomReference.java: Imported from classpath. * java/lang/ref/SoftReference.java: Ditto. * java/lang/ref/Reference.java: Ditto. * java/lang/ref/WeakReference.java: Ditto. * java/lang/ref/ReferenceQueue.java: Ditto. From-SVN: r38183
This commit is contained in:
parent
a0932f7d1a
commit
488d42af6f
18 changed files with 2942 additions and 2062 deletions
|
@ -332,14 +332,14 @@ public abstract class AbstractCollection implements Collection
|
|||
{
|
||||
Iterator itr = iterator();
|
||||
int size = size();
|
||||
String r = "[";
|
||||
StringBuffer r = new StringBuffer("[");
|
||||
for (int pos = 0; pos < size; pos++)
|
||||
{
|
||||
r += itr.next();
|
||||
r.append(itr.next());
|
||||
if (pos < size - 1)
|
||||
r += ", ";
|
||||
r.append(", ");
|
||||
}
|
||||
r += "]";
|
||||
return r;
|
||||
r.append("]");
|
||||
return r.toString();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -227,15 +227,18 @@ public abstract class AbstractMap implements Map
|
|||
{
|
||||
Iterator entries = entrySet().iterator();
|
||||
int size = size();
|
||||
String r = "{";
|
||||
StringBuffer r = new StringBuffer("{");
|
||||
for (int pos = 0; pos < size; pos++)
|
||||
{
|
||||
r += entries.next();
|
||||
// Append the toString value of the entries rather than calling
|
||||
// getKey/getValue. This is more efficient and it matches the JDK
|
||||
// behaviour.
|
||||
r.append(entries.next());
|
||||
if (pos < size - 1)
|
||||
r += ", ";
|
||||
r.append(", ");
|
||||
}
|
||||
r += "}";
|
||||
return r;
|
||||
r.append("}");
|
||||
return r.toString();
|
||||
}
|
||||
|
||||
public Collection values()
|
||||
|
|
|
@ -38,7 +38,6 @@ package java.util;
|
|||
*/
|
||||
public abstract class AbstractSet extends AbstractCollection implements Set
|
||||
{
|
||||
|
||||
/**
|
||||
* Tests whether the given object is equal to this Set. This implementation
|
||||
* first checks whether this set <em>is</em> the given object, and returns
|
||||
|
|
|
@ -1,135 +0,0 @@
|
|||
/* BasicMapEntry.java -- a class providing a plain-vanilla implementation of
|
||||
the Map.Entry interface; could be used anywhere in java.util
|
||||
Copyright (C) 1998 Free Software Foundation, Inc.
|
||||
|
||||
This file is part of GNU Classpath.
|
||||
|
||||
GNU Classpath is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2, or (at your option)
|
||||
any later version.
|
||||
|
||||
GNU Classpath is distributed in the hope that it will be useful, but
|
||||
WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with GNU Classpath; see the file COPYING. If not, write to the
|
||||
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
|
||||
02111-1307 USA.
|
||||
|
||||
As a special exception, if you link this library with other files to
|
||||
produce an executable, this library does not by itself cause the
|
||||
resulting executable to be covered by the GNU General Public License.
|
||||
This exception does not however invalidate any other reasons why the
|
||||
executable file might be covered by the GNU General Public License. */
|
||||
|
||||
|
||||
package java.util;
|
||||
|
||||
/**
|
||||
* a class which implements Map.Entry
|
||||
*
|
||||
* @author Jon Zeppieri
|
||||
* @version $Revision: 1.3 $
|
||||
* @modified $Id: BasicMapEntry.java,v 1.3 2000/03/15 21:59:07 rao Exp $
|
||||
*/
|
||||
class BasicMapEntry implements Map.Entry
|
||||
{
|
||||
/** the key */
|
||||
Object key;
|
||||
/** the value */
|
||||
Object value;
|
||||
|
||||
/**
|
||||
* construct a new BasicMapEntry with the given key and value
|
||||
*
|
||||
* @param newKey the key of this Entry
|
||||
* @param newValue the value of this Entry
|
||||
*/
|
||||
BasicMapEntry(Object newKey, Object newValue)
|
||||
{
|
||||
key = newKey;
|
||||
value = newValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns true if <pre>o</pre> is a Map.Entry and
|
||||
* <pre>
|
||||
* (((o.getKey == null) ? (key == null) :
|
||||
* o.getKey().equals(key)) &&
|
||||
* ((o.getValue() == null) ? (value == null) :
|
||||
* o.getValue().equals(value)))
|
||||
* </pre>
|
||||
*
|
||||
* NOTE: the calls to getKey() and getValue() in this implementation
|
||||
* are <i>NOT</i> superfluous and should not be removed. They insure
|
||||
* that subclasses such as HashMapEntry work correctly
|
||||
*
|
||||
* @param o the Object being tested for equality
|
||||
*/
|
||||
public boolean equals(Object o)
|
||||
{
|
||||
Map.Entry tester;
|
||||
Object oTestingKey, oTestingValue;
|
||||
Object oKey, oValue;
|
||||
if (o instanceof Map.Entry)
|
||||
{
|
||||
tester = (Map.Entry) o;
|
||||
oKey = getKey();
|
||||
oValue = getValue();
|
||||
oTestingKey = tester.getKey();
|
||||
oTestingValue = tester.getValue();
|
||||
return (((oTestingKey == null) ? (oKey == null) :
|
||||
oTestingKey.equals(oKey)) &&
|
||||
((oTestingValue == null) ? (oValue == null) :
|
||||
oTestingValue.equals(oValue)));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** returns the key */
|
||||
public Object getKey()
|
||||
{
|
||||
return key;
|
||||
}
|
||||
|
||||
/** returns the value */
|
||||
public Object getValue()
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
/** the hashCode() for a Map.Entry is
|
||||
* <pre>
|
||||
* ((getKey() == null) ? 0 : getKey().hashCode()) ^
|
||||
* ((getValue() == null) ? 0 : getValue().hashCode());
|
||||
* </pre>
|
||||
*
|
||||
* NOTE: the calls to getKey() and getValue() in this implementation
|
||||
* are <i>NOT</i> superfluous and should not be removed. They insure
|
||||
* that subclasses such as HashMapEntry work correctly
|
||||
*/
|
||||
public int hashCode()
|
||||
{
|
||||
Object oKey = getKey();
|
||||
Object oValue = getValue();
|
||||
return ((oKey == null) ? 0 : oKey.hashCode()) ^
|
||||
((oValue == null) ? 0 : oValue.hashCode());
|
||||
}
|
||||
|
||||
/**
|
||||
* sets the value of this Map.Entry
|
||||
*
|
||||
* @param newValue the new value of this Map.Entry
|
||||
*/
|
||||
public Object setValue(Object newValue)
|
||||
throws java.lang.UnsupportedOperationException, ClassCastException,
|
||||
IllegalArgumentException, NullPointerException
|
||||
{
|
||||
Object oVal = value;
|
||||
value = newValue;
|
||||
return oVal;
|
||||
}
|
||||
}
|
|
@ -1,199 +0,0 @@
|
|||
/* Bucket.java -- a class providing a hash-bucket data structure
|
||||
(a lightweight linked list)
|
||||
Copyright (C) 1998, 2000 Free Software Foundation, Inc.
|
||||
|
||||
This file is part of GNU Classpath.
|
||||
|
||||
GNU Classpath is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2, or (at your option)
|
||||
any later version.
|
||||
|
||||
GNU Classpath is distributed in the hope that it will be useful, but
|
||||
WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with GNU Classpath; see the file COPYING. If not, write to the
|
||||
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
|
||||
02111-1307 USA.
|
||||
|
||||
As a special exception, if you link this library with other files to
|
||||
produce an executable, this library does not by itself cause the
|
||||
resulting executable to be covered by the GNU General Public License.
|
||||
This exception does not however invalidate any other reasons why the
|
||||
executable file might be covered by the GNU General Public License. */
|
||||
|
||||
|
||||
package java.util;
|
||||
|
||||
/**
|
||||
* a class representing a simple, lightweight linked-list, using Node
|
||||
* objects as its linked nodes; this is used by Hashtable and HashMap
|
||||
*
|
||||
* @author Jon Zeppieri
|
||||
* @version $Revision: 1.3 $
|
||||
* @modified $Id: Bucket.java,v 1.3 2000/03/15 21:59:08 rao Exp $
|
||||
*/
|
||||
class Bucket
|
||||
{
|
||||
/** the first node of the lined list, originally null */
|
||||
Node first;
|
||||
|
||||
/** trivial constructor for a Bucket */
|
||||
Bucket()
|
||||
{
|
||||
}
|
||||
|
||||
/** add this key / value pair to the list
|
||||
*
|
||||
* @param newNode a Node object to be added to this list
|
||||
* @return the old value mapped to the key if there was one,
|
||||
* otherwise null.
|
||||
*/
|
||||
Object add(Node newNode)
|
||||
{
|
||||
Object oKey;
|
||||
Object oTestKey = newNode.getKey();
|
||||
Node it = first;
|
||||
Node prev = null;
|
||||
if (it == null) // if the list is empty (the ideal case), we make a new single-node list
|
||||
{
|
||||
first = newNode;
|
||||
return null;
|
||||
}
|
||||
else // otherwise try to find where this key already exists in the list,
|
||||
{// and if it does, replace the value with the new one (and return the old one)
|
||||
while (it != null)
|
||||
{
|
||||
oKey = it.getKey();
|
||||
if ((oKey == null) ? (oTestKey == null) :
|
||||
oKey.equals(oTestKey))
|
||||
{
|
||||
Object oldValue = it.value;
|
||||
it.value = newNode.getValue();
|
||||
return oldValue;
|
||||
}
|
||||
prev = it;
|
||||
it = it.next;
|
||||
}
|
||||
prev.next = newNode; // otherwise, just stick this at the
|
||||
return null; // end of the list
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* remove a Map.Entry in this list with the supplied key and return its value,
|
||||
* if it exists, else return null
|
||||
*
|
||||
* @param key the key we are looking for in this list
|
||||
*/
|
||||
Object removeByKey(Object key)
|
||||
{
|
||||
Object oEntryKey;
|
||||
Node prev = null;
|
||||
Node it = first;
|
||||
while (it != null)
|
||||
{
|
||||
oEntryKey = it.getKey();
|
||||
if ((oEntryKey == null) ? (key == null) : oEntryKey.equals(key))
|
||||
{
|
||||
if (prev == null) // we are removing the first element
|
||||
first = it.next;
|
||||
else
|
||||
prev.next = it.next;
|
||||
return it.getValue();
|
||||
}
|
||||
else
|
||||
{
|
||||
prev = it;
|
||||
it = it.next;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* return the value which the supplied key maps to, if it maps to anything in this list,
|
||||
* otherwise, return null
|
||||
*
|
||||
* @param key the key mapping to a value that we are looking for
|
||||
*/
|
||||
Object getValueByKey(Object key)
|
||||
{
|
||||
Node entry = getEntryByKey(key);
|
||||
return (entry == null) ? null : entry.getValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* return the Map.Entry which the supplied key is a part of, if such a Map.Entry exists,
|
||||
* null otherwise
|
||||
*
|
||||
* this method is important for HashMap, which can hold null values and the null key
|
||||
*
|
||||
* @param key the key for which we are finding the corresponding Map.Entry
|
||||
*/
|
||||
Node getEntryByKey(Object key)
|
||||
{
|
||||
Object oEntryKey;
|
||||
Node it = first;
|
||||
while (it != null)
|
||||
{
|
||||
oEntryKey = it.getKey();
|
||||
if ((oEntryKey == null) ? (key == null) : oEntryKey.equals(key))
|
||||
return it;
|
||||
it = it.next;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* return true if this list has a Map.Entry whose value equals() the supplied value
|
||||
*
|
||||
* @param value the value we are looking to match in this list
|
||||
*/
|
||||
boolean containsValue(Object value)
|
||||
{
|
||||
Object oEntryValue;
|
||||
Node it = first;
|
||||
while (it != null)
|
||||
{
|
||||
oEntryValue = it.getValue();
|
||||
if ((oEntryValue == null) ? (value == null) : oEntryValue.equals(value))
|
||||
return true;
|
||||
it = it.next;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// INNSER CLASSES ----------------------------------------------------------
|
||||
|
||||
/**
|
||||
* a class represnting a node in our lightweight linked-list
|
||||
* that we use for hash buckets; a Node object contains a Map.Entry as its
|
||||
* <pre>value</pre> property and a reference (possibly, even hopefully, null)
|
||||
* to another Node as its <pre>next</pre> property.
|
||||
*
|
||||
* There <i>is</i> a reason for not using a highly generic "LinkedNode" type
|
||||
* class: we want to eliminate runtime typechecks.
|
||||
*
|
||||
* @author Jon Zeppieri
|
||||
* @version $Revision: 1.3 $
|
||||
* @modified $Id: Bucket.java,v 1.3 2000/03/15 21:59:08 rao Exp $
|
||||
*/
|
||||
static class Node extends BasicMapEntry implements Map.Entry
|
||||
{
|
||||
/** a reference to the next node in the linked list */
|
||||
Node next;
|
||||
|
||||
/** non-trivial contructor -- sets the <pre>value</pre> of the Bucket upon instantiation */
|
||||
Node(Object key, Object value)
|
||||
{
|
||||
super(key, value);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
// EOF ------------------------------------------------------------------------
|
||||
}
|
|
@ -149,10 +149,10 @@ public class Collections
|
|||
// is sequential-access.
|
||||
if (l instanceof AbstractSequentialList)
|
||||
{
|
||||
ListIterator i = l.listIterator();
|
||||
while (i.hasNext())
|
||||
ListIterator itr = l.listIterator();
|
||||
for (int i = l.size() - 1; i >= 0; --i)
|
||||
{
|
||||
final int d = compare(key, i.next(), c);
|
||||
final int d = compare(key, itr.next(), c);
|
||||
if (d == 0)
|
||||
{
|
||||
return pos;
|
||||
|
@ -264,10 +264,18 @@ public class Collections
|
|||
{
|
||||
Iterator i1 = source.iterator();
|
||||
ListIterator i2 = dest.listIterator();
|
||||
while (i1.hasNext())
|
||||
|
||||
try
|
||||
{
|
||||
i2.next();
|
||||
i2.set(i1.next());
|
||||
for (int i = source.size() - 1; i >= 0; --i)
|
||||
{
|
||||
i2.next();
|
||||
i2.set(i1.next());
|
||||
}
|
||||
}
|
||||
catch (NoSuchElementException x)
|
||||
{
|
||||
throw new IndexOutOfBoundsException("Source doesn't fit in dest.");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -305,11 +313,11 @@ public class Collections
|
|||
*/
|
||||
public static void fill(List l, Object val)
|
||||
{
|
||||
ListIterator i = l.listIterator();
|
||||
while (i.hasNext())
|
||||
ListIterator itr = l.listIterator();
|
||||
for (int i = l.size() - 1; i >= 0; --i)
|
||||
{
|
||||
i.next();
|
||||
i.set(val);
|
||||
itr.next();
|
||||
itr.set(val);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -326,11 +334,12 @@ public class Collections
|
|||
*/
|
||||
public static Object max(Collection c)
|
||||
{
|
||||
Iterator i = c.iterator();
|
||||
Comparable max = (Comparable) i.next(); // throws NoSuchElementException
|
||||
while (i.hasNext())
|
||||
Iterator itr = c.iterator();
|
||||
Comparable max = (Comparable) itr.next(); // throws NoSuchElementException
|
||||
int csize = c.size();
|
||||
for (int i = 1; i < csize; i++)
|
||||
{
|
||||
Object o = i.next();
|
||||
Object o = itr.next();
|
||||
if (max.compareTo(o) < 0)
|
||||
{
|
||||
max = (Comparable) o;
|
||||
|
@ -352,15 +361,14 @@ public class Collections
|
|||
*/
|
||||
public static Object max(Collection c, Comparator order)
|
||||
{
|
||||
Iterator i = c.iterator();
|
||||
Object max = i.next(); // throws NoSuchElementException
|
||||
while (i.hasNext())
|
||||
Iterator itr = c.iterator();
|
||||
Object max = itr.next(); // throws NoSuchElementException
|
||||
int csize = c.size();
|
||||
for (int i = 1; i < csize; i++)
|
||||
{
|
||||
Object o = i.next();
|
||||
Object o = itr.next();
|
||||
if (order.compare(max, o) < 0)
|
||||
{
|
||||
max = o;
|
||||
}
|
||||
max = o;
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
@ -378,15 +386,14 @@ public class Collections
|
|||
*/
|
||||
public static Object min(Collection c)
|
||||
{
|
||||
Iterator i = c.iterator();
|
||||
Comparable min = (Comparable) i.next(); // throws NoSuchElementException
|
||||
while (i.hasNext())
|
||||
Iterator itr = c.iterator();
|
||||
Comparable min = (Comparable) itr.next(); // throws NoSuchElementException
|
||||
int csize = c.size();
|
||||
for (int i = 1; i < csize; i++)
|
||||
{
|
||||
Object o = i.next();
|
||||
Object o = itr.next();
|
||||
if (min.compareTo(o) > 0)
|
||||
{
|
||||
min = (Comparable) o;
|
||||
}
|
||||
min = (Comparable) o;
|
||||
}
|
||||
return min;
|
||||
}
|
||||
|
@ -404,15 +411,14 @@ public class Collections
|
|||
*/
|
||||
public static Object min(Collection c, Comparator order)
|
||||
{
|
||||
Iterator i = c.iterator();
|
||||
Object min = i.next(); // throws NoSuchElementExcception
|
||||
while (i.hasNext())
|
||||
Iterator itr = c.iterator();
|
||||
Object min = itr.next(); // throws NoSuchElementExcception
|
||||
int csize = c.size();
|
||||
for (int i = 1; i < csize; i++)
|
||||
{
|
||||
Object o = i.next();
|
||||
Object o = itr.next();
|
||||
if (order.compare(min, o) > 0)
|
||||
{
|
||||
min = o;
|
||||
}
|
||||
min = o;
|
||||
}
|
||||
return min;
|
||||
}
|
||||
|
@ -468,12 +474,16 @@ public class Collections
|
|||
public static void reverse(List l)
|
||||
{
|
||||
ListIterator i1 = l.listIterator();
|
||||
ListIterator i2 = l.listIterator(l.size());
|
||||
while (i1.nextIndex() < i2.previousIndex())
|
||||
int pos1 = 0;
|
||||
int pos2 = l.size();
|
||||
ListIterator i2 = l.listIterator(pos2);
|
||||
while (pos1 < pos2)
|
||||
{
|
||||
Object o = i1.next();
|
||||
i1.set(i2.previous());
|
||||
i2.set(o);
|
||||
++pos1;
|
||||
--pos2;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -513,9 +523,24 @@ public class Collections
|
|||
*/
|
||||
public static void shuffle(List l)
|
||||
{
|
||||
shuffle(l, new Random());
|
||||
if (defaultRandom == null)
|
||||
{
|
||||
synchronized (Collections.class)
|
||||
{
|
||||
if (defaultRandom == null)
|
||||
defaultRandom = new Random();
|
||||
}
|
||||
}
|
||||
shuffle(l, defaultRandom);
|
||||
}
|
||||
|
||||
/** Cache a single Random object for use by shuffle(List). This improves
|
||||
* performance as well as ensuring that sequential calls to shuffle() will
|
||||
* not result in the same shuffle order occuring: the resolution of
|
||||
* System.currentTimeMillis() is not sufficient to guarantee a unique seed.
|
||||
*/
|
||||
private static Random defaultRandom = null;
|
||||
|
||||
/**
|
||||
* Shuffle a list according to a given source of randomness. The algorithm
|
||||
* used iterates backwards over the list, swapping each element with an
|
||||
|
@ -541,20 +566,21 @@ public class Collections
|
|||
public static void shuffle(List l, Random r)
|
||||
{
|
||||
Object[] a = l.toArray(); // Dump l into an array
|
||||
ListIterator i = l.listIterator(l.size());
|
||||
int lsize = l.size();
|
||||
ListIterator i = l.listIterator(lsize);
|
||||
|
||||
// Iterate backwards over l
|
||||
while (i.hasPrevious())
|
||||
for (int pos = lsize - 1; pos >= 0; --pos)
|
||||
{
|
||||
// Obtain a random position to swap with. nextIndex is used so that the
|
||||
// Obtain a random position to swap with. pos + 1 is used so that the
|
||||
// range of the random number includes the current position.
|
||||
int swap = r.nextInt(i.nextIndex());
|
||||
int swap = r.nextInt(pos + 1);
|
||||
|
||||
// Swap the swapth element of the array with the next element of the
|
||||
// list.
|
||||
Object o = a[swap];
|
||||
a[swap] = a[i.previousIndex()];
|
||||
a[i.previousIndex()] = o;
|
||||
a[swap] = a[pos];
|
||||
a[pos] = o;
|
||||
|
||||
// Set the element in the original list accordingly.
|
||||
i.previous();
|
||||
|
@ -658,7 +684,7 @@ public class Collections
|
|||
{
|
||||
public Set entrySet()
|
||||
{
|
||||
return singleton(new BasicMapEntry(key, value));
|
||||
return singleton(new HashMap.Entry(key, value));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
File diff suppressed because it is too large
Load diff
221
libjava/java/util/HashSet.java
Normal file
221
libjava/java/util/HashSet.java
Normal file
|
@ -0,0 +1,221 @@
|
|||
/* HashSet.java -- a class providing a HashMap-backet Set
|
||||
Copyright (C) 1998, 1999 Free Software Foundation, Inc.
|
||||
|
||||
This file is part of GNU Classpath.
|
||||
|
||||
GNU Classpath is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2, or (at your option)
|
||||
any later version.
|
||||
|
||||
GNU Classpath is distributed in the hope that it will be useful, but
|
||||
WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with GNU Classpath; see the file COPYING. If not, write to the
|
||||
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
|
||||
02111-1307 USA.
|
||||
|
||||
As a special exception, if you link this library with other files to
|
||||
produce an executable, this library does not by itself cause the
|
||||
resulting executable to be covered by the GNU General Public License.
|
||||
This exception does not however invalidate any other reasons why the
|
||||
executable file might be covered by the GNU General Public License. */
|
||||
|
||||
|
||||
package java.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Serializable;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
|
||||
/**
|
||||
* This class provides a HashMap-backed implementation of the
|
||||
* Set interface.
|
||||
*
|
||||
* Each element in the Set is a key in the backing HashMap; each key
|
||||
* maps to a static token, denoting that the key does, in fact, exist.
|
||||
*
|
||||
* Most operations are O(1), assuming no hash collisions. In the worst
|
||||
* case (where all hases collide), operations are O(n).
|
||||
*
|
||||
* HashSet is a part of the JDK1.2 Collections API.
|
||||
*
|
||||
* @author Jon Zeppieri
|
||||
* @version $Revision: 1.5 $
|
||||
* @modified $Id: HashSet.java,v 1.5 2000/10/26 10:19:00 bryce Exp $
|
||||
*/
|
||||
public class HashSet extends AbstractSet
|
||||
implements Set, Cloneable, Serializable
|
||||
{
|
||||
/** the HashMap which backs this Set */
|
||||
transient HashMap map;
|
||||
static final long serialVersionUID = -5024744406713321676L;
|
||||
|
||||
/**
|
||||
* construct a new, empty HashSet whose backing HashMap has the default
|
||||
* capacity and loadFacor
|
||||
*/
|
||||
public HashSet()
|
||||
{
|
||||
map = new HashMap();
|
||||
}
|
||||
|
||||
/**
|
||||
* construct a new, empty HashSet whose backing HashMap has the supplied
|
||||
* capacity and the default load factor
|
||||
*
|
||||
* @param initialCapacity the initial capacity of the backing
|
||||
* HashMap
|
||||
*/
|
||||
public HashSet(int initialCapacity)
|
||||
{
|
||||
map = new HashMap(initialCapacity);
|
||||
}
|
||||
|
||||
/**
|
||||
* construct a new, empty HashSet whose backing HashMap has the supplied
|
||||
* capacity and load factor
|
||||
*
|
||||
* @param initialCapacity the initial capacity of the backing
|
||||
* HashMap
|
||||
* @param loadFactor the load factor of the backing HashMap
|
||||
*/
|
||||
public HashSet(int initialCapacity, float loadFactor)
|
||||
{
|
||||
map = new HashMap(initialCapacity, loadFactor);
|
||||
}
|
||||
|
||||
/**
|
||||
* construct a new HashSet with the same elements as are in the supplied
|
||||
* collection (eliminating any duplicates, of course; the backing HashMap
|
||||
* will have the default capacity and load factor
|
||||
*
|
||||
* @param c a collection containing the elements with
|
||||
* which this set will be initialized
|
||||
*/
|
||||
public HashSet(Collection c)
|
||||
{
|
||||
map = new HashMap();
|
||||
addAll(c);
|
||||
}
|
||||
|
||||
/**
|
||||
* adds the given Object to the set if it is not already in the Set,
|
||||
* returns true if teh element was added, false otherwise
|
||||
*
|
||||
* @param o the Object to add to this Set
|
||||
*/
|
||||
public boolean add(Object o)
|
||||
{
|
||||
return (map.put(o, Boolean.TRUE) == null);
|
||||
}
|
||||
|
||||
/**
|
||||
* empties this Set of all elements; this is a fast operation [O(1)]
|
||||
*/
|
||||
public void clear()
|
||||
{
|
||||
map.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* returns a shallow copy of this Set (the Set itself is cloned; its
|
||||
* elements are not)
|
||||
*/
|
||||
public Object clone()
|
||||
{
|
||||
HashSet copy = null;
|
||||
try
|
||||
{
|
||||
copy = (HashSet) super.clone();
|
||||
copy.map = (HashMap) map.clone();
|
||||
}
|
||||
catch (CloneNotSupportedException ex)
|
||||
{
|
||||
}
|
||||
|
||||
return copy;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns true if the supplied element is in this Set, false otherwise
|
||||
*
|
||||
* @param o the Object whose presence in this Set we are testing for
|
||||
*/
|
||||
public boolean contains(Object o)
|
||||
{
|
||||
return map.containsKey(o);
|
||||
}
|
||||
|
||||
/**
|
||||
* returns true if this set has no elements in it (size() == 0)
|
||||
*/
|
||||
public boolean isEmpty()
|
||||
{
|
||||
return map.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* returns an Iterator over the elements of this Set; the Iterator allows
|
||||
* removal of elements
|
||||
*/
|
||||
public Iterator iterator()
|
||||
{
|
||||
return map.keySet().iterator();
|
||||
}
|
||||
|
||||
/**
|
||||
* removes the supplied Object from this Set if it is in the Set; returns
|
||||
* true if an element was removed, false otherwise
|
||||
*/
|
||||
public boolean remove(Object o)
|
||||
{
|
||||
return (map.remove(o) != null);
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the number of elements in this Set
|
||||
*/
|
||||
public int size()
|
||||
{
|
||||
return map.size();
|
||||
}
|
||||
|
||||
/** Serialize this Object in a manner which is binary-compatible with the
|
||||
* JDK */
|
||||
private void writeObject(ObjectOutputStream s) throws IOException
|
||||
{
|
||||
Iterator it = iterator();
|
||||
s.writeInt(map.buckets.length);
|
||||
s.writeFloat(map.loadFactor);
|
||||
s.writeInt(map.size);
|
||||
while (it.hasNext())
|
||||
s.writeObject(it.next());
|
||||
}
|
||||
|
||||
/** Deserialize this Object in a manner which is binary-compatible with
|
||||
* the JDK */
|
||||
private void readObject(ObjectInputStream s) throws IOException,
|
||||
ClassNotFoundException
|
||||
{
|
||||
int i, size, capacity;
|
||||
float loadFactor;
|
||||
Object element;
|
||||
|
||||
capacity = s.readInt();
|
||||
loadFactor = s.readFloat();
|
||||
size = s.readInt();
|
||||
|
||||
map = new HashMap(capacity, loadFactor);
|
||||
|
||||
for (i = 0; i < size; i++)
|
||||
{
|
||||
element = s.readObject();
|
||||
map.put(element, Boolean.TRUE);
|
||||
}
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load diff
731
libjava/java/util/WeakHashMap.java
Normal file
731
libjava/java/util/WeakHashMap.java
Normal file
|
@ -0,0 +1,731 @@
|
|||
/* java.util.WeakHashMap
|
||||
Copyright (C) 1999, 2000 Free Software Foundation, Inc.
|
||||
|
||||
This file is part of GNU Classpath.
|
||||
|
||||
GNU Classpath is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2, or (at your option)
|
||||
any later version.
|
||||
|
||||
GNU Classpath is distributed in the hope that it will be useful, but
|
||||
WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with GNU Classpath; see the file COPYING. If not, write to the
|
||||
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
|
||||
02111-1307 USA.
|
||||
|
||||
As a special exception, if you link this library with other files to
|
||||
produce an executable, this library does not by itself cause the
|
||||
resulting executable to be covered by the GNU General Public License.
|
||||
This exception does not however invalidate any other reasons why the
|
||||
executable file might be covered by the GNU General Public License. */
|
||||
|
||||
|
||||
package java.util;
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.lang.ref.ReferenceQueue;
|
||||
|
||||
/**
|
||||
* A weak hash map has only weak references to the key. This means
|
||||
* that it allows the key to be garbage collected if they are not used
|
||||
* otherwise. If this happens, the weak hash map will eventually
|
||||
* remove the whole entry from this map. <br>
|
||||
*
|
||||
* A weak hash map makes most sense, if the keys doesn't override the
|
||||
* <code>equals</code>-method: If there is no other reference to the
|
||||
* key nobody can ever look up the key in this table and so the entry
|
||||
* can be removed. This table also works, if the <code>equals</code>
|
||||
* method is overloaded, e.g. with Strings as keys, but you should be
|
||||
* prepared that some entries disappear spontaneously. <br>
|
||||
*
|
||||
* You should also be prepared that this hash map behaves very
|
||||
* strange: The size of this map may spontaneously shrink (even if you
|
||||
* use a synchronized map and synchronize it); it behaves as if
|
||||
* another thread removes entries from this table without
|
||||
* synchronizations. The entry set returned by <code>entrySet</code>
|
||||
* has similar phenomenons: The size may spontaneously shrink, or an
|
||||
* entry, that was in the set before, suddenly disappears. <br>
|
||||
*
|
||||
* A weak hash map is not meant for caches; use a normal map, with
|
||||
* soft references as values instead. <br>
|
||||
*
|
||||
* The weak hash map supports null values and null keys. Null keys
|
||||
* are never deleted from the map (except explictly of course).
|
||||
* The performance of the methods are similar to that of a hash map. <br>
|
||||
*
|
||||
* The value object are strongly referenced by this table. So if a
|
||||
* value object maintains a strong reference to the key (either direct
|
||||
* or indirect) the key will never be removed from this map. According
|
||||
* to Sun, this problem may be fixed in a future release. It is not
|
||||
* possible to do it with the jdk 1.2 reference model, though.
|
||||
*
|
||||
* @since jdk1.2
|
||||
* @author Jochen Hoenicke
|
||||
* @see HashMap
|
||||
* @see WeakReference */
|
||||
public class WeakHashMap extends AbstractMap implements Map
|
||||
{
|
||||
/**
|
||||
* The default capacity for an instance of HashMap.
|
||||
* Sun's documentation mildly suggests that this (11) is the correct
|
||||
* value.
|
||||
*/
|
||||
private static final int DEFAULT_CAPACITY = 11;
|
||||
|
||||
/**
|
||||
* The default load factor of a HashMap
|
||||
*/
|
||||
private static final float DEFAULT_LOAD_FACTOR = 0.75F;
|
||||
|
||||
/**
|
||||
* This is used instead of the key value <i>null</i>. It is needed
|
||||
* to distinguish between an null key and a removed key.
|
||||
*/
|
||||
private static final Object NULL_KEY = new Object();
|
||||
|
||||
/**
|
||||
* The reference queue where our buckets (which are WeakReferences) are
|
||||
* registered to.
|
||||
*/
|
||||
private ReferenceQueue queue;
|
||||
|
||||
/**
|
||||
* The number of entries in this hash map.
|
||||
*/
|
||||
private int size;
|
||||
|
||||
/**
|
||||
* The load factor of this WeakHashMap. This is the maximum ratio of
|
||||
* size versus number of buckets. If size grows the number of buckets
|
||||
* must grow, too.
|
||||
*/
|
||||
private float loadFactor;
|
||||
|
||||
/**
|
||||
* The rounded product of the capacity (i.e. number of buckets) and
|
||||
* the load factor. When the number of elements exceeds the
|
||||
* threshold, the HashMap calls <pre>rehash()</pre>.
|
||||
*/
|
||||
private int threshold;
|
||||
|
||||
/**
|
||||
* The number of structural modifications. This is used by
|
||||
* iterators, to see if they should fail. This doesn't count
|
||||
* the silent key removals, when a weak reference is cleared
|
||||
* by the garbage collection. Instead the iterators must make
|
||||
* sure to have strong references to the entries they rely on.
|
||||
*/
|
||||
private int modCount;
|
||||
|
||||
/**
|
||||
* The entry set. There is only one instance per hashmap, namely
|
||||
* theEntrySet. Note that the entry set may silently shrink, just
|
||||
* like the WeakHashMap.
|
||||
*/
|
||||
private class WeakEntrySet extends AbstractSet
|
||||
{
|
||||
/**
|
||||
* Returns the size of this set.
|
||||
*/
|
||||
public int size()
|
||||
{
|
||||
return size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an iterator for all entries.
|
||||
*/
|
||||
public Iterator iterator()
|
||||
{
|
||||
return new Iterator()
|
||||
{
|
||||
/**
|
||||
* The entry that was returned by the last
|
||||
* <code>next()</code> call. This is also the entry whose
|
||||
* bucket should be removed by the <code>remove</code> call. <br>
|
||||
*
|
||||
* It is null, if the <code>next</code> method wasn't
|
||||
* called yet, or if the entry was already removed. <br>
|
||||
*
|
||||
* Remembering this entry here will also prevent it from
|
||||
* being removed under us, since the entry strongly refers
|
||||
* to the key.
|
||||
*/
|
||||
WeakBucket.Entry lastEntry;
|
||||
|
||||
/**
|
||||
* The entry that will be returned by the next
|
||||
* <code>next()</code> call. It is <code>null</code> if there
|
||||
* is no further entry. <br>
|
||||
*
|
||||
* Remembering this entry here will also prevent it from
|
||||
* being removed under us, since the entry strongly refers
|
||||
* to the key.
|
||||
*/
|
||||
WeakBucket.Entry nextEntry = findNext(null);
|
||||
|
||||
/**
|
||||
* The known number of modification to the list, if it differs
|
||||
* from the real number, we through an exception.
|
||||
*/
|
||||
int knownMod = modCount;
|
||||
|
||||
/**
|
||||
* Check the known number of modification to the number of
|
||||
* modifications of the table. If it differs from the real
|
||||
* number, we throw an exception.
|
||||
* @exception ConcurrentModificationException if the number
|
||||
* of modifications doesn't match.
|
||||
*/
|
||||
private void checkMod()
|
||||
{
|
||||
/* This method will get inlined */
|
||||
if (knownMod != modCount)
|
||||
throw new ConcurrentModificationException();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a strong reference to the next entry after
|
||||
* lastBucket.
|
||||
* @param lastBucket the previous bucket, or null if we should
|
||||
* get the first entry.
|
||||
* @return the next entry.
|
||||
*/
|
||||
private WeakBucket.Entry findNext(WeakBucket.Entry lastEntry)
|
||||
{
|
||||
int slot;
|
||||
WeakBucket nextBucket;
|
||||
if (lastEntry != null)
|
||||
{
|
||||
nextBucket = lastEntry.getBucket().next;
|
||||
slot = lastEntry.getBucket().slot;
|
||||
}
|
||||
else
|
||||
{
|
||||
nextBucket = buckets[0];
|
||||
slot = 0;
|
||||
}
|
||||
|
||||
while (true)
|
||||
{
|
||||
while (nextBucket != null)
|
||||
{
|
||||
WeakBucket.Entry entry = nextBucket.getEntry();
|
||||
if (entry != null)
|
||||
/* This is the next entry */
|
||||
return entry;
|
||||
|
||||
/* entry was cleared, try next */
|
||||
nextBucket = nextBucket.next;
|
||||
}
|
||||
|
||||
slot++;
|
||||
if (slot == buckets.length)
|
||||
/* No more buckets, we are through */
|
||||
return null;
|
||||
|
||||
nextBucket = buckets[slot];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Checks if there are more entries.
|
||||
* @return true, iff there are more elements.
|
||||
* @exception IllegalModificationException if the hash map was
|
||||
* modified.
|
||||
*/
|
||||
public boolean hasNext()
|
||||
{
|
||||
cleanQueue();
|
||||
checkMod();
|
||||
return (nextEntry != null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the next entry.
|
||||
* @return the next entry.
|
||||
* @exception IllegalModificationException if the hash map was
|
||||
* modified.
|
||||
* @exception NoSuchElementException if there is no entry.
|
||||
*/
|
||||
public Object next()
|
||||
{
|
||||
cleanQueue();
|
||||
checkMod();
|
||||
if (nextEntry == null)
|
||||
throw new NoSuchElementException();
|
||||
lastEntry = nextEntry;
|
||||
nextEntry = findNext(lastEntry);
|
||||
return lastEntry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the last returned entry from this set. This will
|
||||
* also remove the bucket of the underlying weak hash map.
|
||||
* @exception IllegalModificationException if the hash map was
|
||||
* modified.
|
||||
* @exception IllegalStateException if <code>next()</code> was
|
||||
* never called or the element was already removed.
|
||||
*/
|
||||
public void remove()
|
||||
{
|
||||
cleanQueue();
|
||||
checkMod();
|
||||
if (lastEntry == null)
|
||||
throw new IllegalStateException();
|
||||
internalRemove(lastEntry.getBucket());
|
||||
lastEntry = null;
|
||||
modCount++;
|
||||
knownMod = modCount;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A bucket is a weak reference to the key, that contains a strong
|
||||
* reference to the value, a pointer to the next bucket and its slot
|
||||
* number. <br>
|
||||
*
|
||||
* It would be cleaner to have a WeakReference as field, instead of
|
||||
* extending it, but if a weak reference get cleared, we only get
|
||||
* the weak reference (by queue.poll) and wouldn't know where to
|
||||
* look for this reference in the hashtable, to remove that entry.
|
||||
*
|
||||
* @author Jochen Hoenicke
|
||||
*/
|
||||
private static class WeakBucket extends WeakReference
|
||||
{
|
||||
/**
|
||||
* The value of this entry. The key is stored in the weak
|
||||
* reference that we extend.
|
||||
*/
|
||||
Object value;
|
||||
|
||||
/**
|
||||
* The next bucket describing another entry that uses the same
|
||||
* slot.
|
||||
*/
|
||||
WeakBucket next;
|
||||
|
||||
/**
|
||||
* The slot of this entry. This should be
|
||||
* <pre>
|
||||
* Math.abs(key.hashCode() % buckets.length)
|
||||
* </pre>
|
||||
* But since the key may be silently removed we have to remember
|
||||
* the slot number.
|
||||
* If this bucket was removed the slot is -1. This marker will
|
||||
* prevent the bucket from being removed twice.
|
||||
*/
|
||||
int slot;
|
||||
|
||||
/**
|
||||
* Creates a new bucket for the given key/value pair and the specified
|
||||
* slot.
|
||||
* @param key the key
|
||||
* @param value the value
|
||||
* @param slot the slot. This must match the slot where this bucket
|
||||
* will be enqueued.
|
||||
*/
|
||||
public WeakBucket(Object key, ReferenceQueue queue, Object value,
|
||||
int slot)
|
||||
{
|
||||
super(key, queue);
|
||||
this.value = value;
|
||||
this.slot = slot;
|
||||
}
|
||||
|
||||
/**
|
||||
* This class gives the <code>Entry</code> representation of the
|
||||
* current bucket. It also keeps a strong reference to the
|
||||
* key; bad things may happen otherwise.
|
||||
*/
|
||||
class Entry implements Map.Entry
|
||||
{
|
||||
/**
|
||||
* The strong ref to the key.
|
||||
*/
|
||||
Object key;
|
||||
|
||||
/**
|
||||
* Creates a new entry for the key.
|
||||
*/
|
||||
public Entry(Object key)
|
||||
{
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the underlying bucket.
|
||||
*/
|
||||
public WeakBucket getBucket()
|
||||
{
|
||||
return WeakBucket.this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the key.
|
||||
*/
|
||||
public Object getKey()
|
||||
{
|
||||
return key == NULL_KEY ? null : key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value.
|
||||
*/
|
||||
public Object getValue()
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* This changes the value. This change takes place in
|
||||
* the underlying hash map.
|
||||
*/
|
||||
public Object setValue(Object newVal)
|
||||
{
|
||||
Object oldVal = value;
|
||||
value = newVal;
|
||||
return oldVal;
|
||||
}
|
||||
|
||||
/**
|
||||
* The hashCode as specified in the Entry interface.
|
||||
*/
|
||||
public int hashCode()
|
||||
{
|
||||
return (key == NULL_KEY ? 0 : key.hashCode())
|
||||
^ (value == null ? 0 : value.hashCode());
|
||||
}
|
||||
|
||||
/**
|
||||
* The equals method as specified in the Entry interface.
|
||||
*/
|
||||
public boolean equals(Object o)
|
||||
{
|
||||
if (o instanceof Map.Entry)
|
||||
{
|
||||
Map.Entry e = (Map.Entry) o;
|
||||
return (key == NULL_KEY
|
||||
? e.getKey() == null : key.equals(e.getKey()))
|
||||
&& (value == null
|
||||
? e.getValue() == null : value.equals(e.getValue()));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This returns the entry stored in this bucket, or null, if the
|
||||
* bucket got cleared in the mean time.
|
||||
*/
|
||||
Entry getEntry()
|
||||
{
|
||||
final Object key = this.get();
|
||||
if (key == null)
|
||||
return null;
|
||||
return new Entry(key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The entry set returned by <code>entrySet()</code>.
|
||||
*/
|
||||
private WeakEntrySet theEntrySet;
|
||||
|
||||
/**
|
||||
* The hash buckets. This are linked lists.
|
||||
*/
|
||||
private WeakBucket[] buckets;
|
||||
|
||||
/**
|
||||
* Creates a new weak hash map with default load factor and default
|
||||
* capacity.
|
||||
*/
|
||||
public WeakHashMap()
|
||||
{
|
||||
this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new weak hash map with default load factor and the given
|
||||
* capacity.
|
||||
* @param initialCapacity the initial capacity
|
||||
*/
|
||||
public WeakHashMap(int initialCapacity)
|
||||
{
|
||||
this(initialCapacity, DEFAULT_LOAD_FACTOR);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new weak hash map with the given initial capacity and
|
||||
* load factor.
|
||||
* @param initialCapacity the initial capacity.
|
||||
* @param loadFactor the load factor (see class description of HashMap).
|
||||
*/
|
||||
public WeakHashMap(int initialCapacity, float loadFactor)
|
||||
{
|
||||
if (initialCapacity < 0 || loadFactor <= 0 || loadFactor > 1)
|
||||
throw new IllegalArgumentException();
|
||||
this.loadFactor = loadFactor;
|
||||
threshold = (int) (initialCapacity * loadFactor);
|
||||
theEntrySet = new WeakEntrySet();
|
||||
queue = new ReferenceQueue();
|
||||
buckets = new WeakBucket[initialCapacity];
|
||||
}
|
||||
|
||||
/**
|
||||
* simply hashes a non-null Object to its array index
|
||||
*/
|
||||
private int hash(Object key)
|
||||
{
|
||||
return Math.abs(key.hashCode() % buckets.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleans the reference queue. This will poll all references (which
|
||||
* are WeakBuckets) from the queue and remove them from this map.
|
||||
* This will not change modCount, even if it modifies the map. The
|
||||
* iterators have to make sure that nothing bad happens. <br>
|
||||
*
|
||||
* Currently the iterator maintains a strong reference to the key, so
|
||||
* that is no problem.
|
||||
*/
|
||||
private void cleanQueue()
|
||||
{
|
||||
Object bucket = queue.poll();
|
||||
while (bucket != null)
|
||||
{
|
||||
internalRemove((WeakBucket) bucket);
|
||||
bucket = queue.poll();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rehashes this hashtable. This will be called by the
|
||||
* <code>add()</code> method if the size grows beyond the threshold.
|
||||
* It will grow the bucket size at least by factor two and allocates
|
||||
* new buckets.
|
||||
*/
|
||||
private void rehash()
|
||||
{
|
||||
WeakBucket[] oldBuckets = buckets;
|
||||
int newsize = buckets.length * 2 + 1; // XXX should be prime.
|
||||
threshold = (int) (newsize * loadFactor);
|
||||
buckets = new WeakBucket[newsize];
|
||||
|
||||
/* Now we have to insert the buckets again.
|
||||
*/
|
||||
for (int i = 0; i < oldBuckets.length; i++)
|
||||
{
|
||||
WeakBucket bucket = oldBuckets[i];
|
||||
WeakBucket nextBucket;
|
||||
while (bucket != null)
|
||||
{
|
||||
nextBucket = bucket.next;
|
||||
|
||||
Object key = bucket.get();
|
||||
if (key == null)
|
||||
{
|
||||
/* This bucket should be removed; it is probably
|
||||
* already on the reference queue. We don't insert it
|
||||
* at all, and mark it as cleared. */
|
||||
bucket.slot = -1;
|
||||
size--;
|
||||
}
|
||||
else
|
||||
{
|
||||
/* add this bucket to its new slot */
|
||||
int slot = hash(key);
|
||||
bucket.slot = slot;
|
||||
bucket.next = buckets[slot];
|
||||
buckets[slot] = bucket;
|
||||
}
|
||||
bucket = nextBucket;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the entry corresponding to key. Since it returns an Entry
|
||||
* it will also prevent the key from being removed under us.
|
||||
* @param key the key. It may be null.
|
||||
* @return The WeakBucket.Entry or null, if the key wasn't found.
|
||||
*/
|
||||
private WeakBucket.Entry internalGet(Object key)
|
||||
{
|
||||
if (key == null)
|
||||
key = NULL_KEY;
|
||||
int slot = hash(key);
|
||||
WeakBucket bucket = buckets[slot];
|
||||
while (bucket != null)
|
||||
{
|
||||
WeakBucket.Entry entry = bucket.getEntry();
|
||||
if (entry != null && key.equals(entry.key))
|
||||
return entry;
|
||||
|
||||
bucket = bucket.next;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a new key/value pair to the hash map.
|
||||
* @param key the key. This mustn't exists in the map. It may be null.
|
||||
* @param value the value.
|
||||
*/
|
||||
private void internalAdd(Object key, Object value)
|
||||
{
|
||||
if (key == null)
|
||||
key = NULL_KEY;
|
||||
int slot = hash(key);
|
||||
WeakBucket bucket = new WeakBucket(key, queue, value, slot);
|
||||
bucket.next = buckets[slot];
|
||||
buckets[slot] = bucket;
|
||||
size++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a bucket from this hash map, if it wasn't removed before
|
||||
* (e.g. one time through rehashing and one time through reference queue)
|
||||
* @param bucket the bucket to remove.
|
||||
*/
|
||||
private void internalRemove(WeakBucket bucket)
|
||||
{
|
||||
int slot = bucket.slot;
|
||||
if (slot == -1)
|
||||
/* this bucket was already removed. */
|
||||
return;
|
||||
|
||||
/* mark the bucket as removed. This is necessary, since the
|
||||
* bucket may be enqueued later by the garbage collection and
|
||||
* internalRemove, will be called a second time.
|
||||
*/
|
||||
bucket.slot = -1;
|
||||
if (buckets[slot] == bucket)
|
||||
buckets[slot] = bucket.next;
|
||||
else
|
||||
{
|
||||
WeakBucket prev = buckets[slot];
|
||||
/* This may throw a NullPointerException. It shouldn't but if
|
||||
* a race condition occured (two threads removing the same
|
||||
* bucket at the same time) it may happen. <br>
|
||||
* But with race condition many much worse things may happen
|
||||
* anyway.
|
||||
*/
|
||||
while (prev.next != bucket)
|
||||
prev = prev.next;
|
||||
prev.next = bucket.next;
|
||||
}
|
||||
size--;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the size of this hash map. Note that the size() may shrink
|
||||
* spontanously, if the some of the keys were only weakly reachable.
|
||||
* @return the number of entries in this hash map.
|
||||
*/
|
||||
public int size()
|
||||
{
|
||||
cleanQueue();
|
||||
return size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if the map is empty. Note that the result may change
|
||||
* spontanously, if all of the keys were only weakly reachable.
|
||||
* @return true, iff the map is empty.
|
||||
*/
|
||||
public boolean isEmpty()
|
||||
{
|
||||
cleanQueue();
|
||||
return size == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if the map contains the given key. Note that the result
|
||||
* may change spontanously, if all the key was only weakly
|
||||
* reachable.
|
||||
* @return true, iff the map contains an entry for the given key.
|
||||
*/
|
||||
public boolean containsKey(Object key)
|
||||
{
|
||||
cleanQueue();
|
||||
return internalGet(key) != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value the key will be mapped to.
|
||||
* @return the value the key was mapped to. It returns null if
|
||||
* the key wasn't in this map, or if the mapped value was explicitly
|
||||
* set to null.
|
||||
*/
|
||||
public Object get(Object key)
|
||||
{
|
||||
cleanQueue();
|
||||
WeakBucket.Entry entry = internalGet(key);
|
||||
return entry == null ? null : entry.getValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a new key/value mapping to this map.
|
||||
* @param key the key. This may be null.
|
||||
* @param value the value. This may be null.
|
||||
* @return the value the key was mapped to previously. It returns
|
||||
* null if the key wasn't in this map, or if the mapped value was
|
||||
* explicitly set to null.
|
||||
*/
|
||||
public Object put(Object key, Object value)
|
||||
{
|
||||
cleanQueue();
|
||||
WeakBucket.Entry entry = internalGet(key);
|
||||
if (entry != null)
|
||||
return entry.setValue(value);
|
||||
|
||||
if (size >= threshold)
|
||||
rehash();
|
||||
|
||||
internalAdd(key, value);
|
||||
modCount++;
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the key and the corresponding value from this map.
|
||||
* @param key the key. This may be null.
|
||||
* @return the value the key was mapped to previously. It returns
|
||||
* null if the key wasn't in this map, or if the mapped value was
|
||||
* explicitly set to null. */
|
||||
public Object remove(Object key)
|
||||
{
|
||||
cleanQueue();
|
||||
WeakBucket.Entry entry = internalGet(key);
|
||||
if (entry == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
internalRemove(entry.getBucket());
|
||||
modCount++;
|
||||
return entry.getValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a set representation of the entries in this map. This
|
||||
* set will not have strong references to the keys, so they can be
|
||||
* silently removed. The returned set has therefore the same
|
||||
* strange behaviour (shrinking size(), disappearing entries) as
|
||||
* this weak hash map.
|
||||
* @return a set representation of the entries. */
|
||||
public Set entrySet()
|
||||
{
|
||||
cleanQueue();
|
||||
return theEntrySet;
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue