diff --git a/optional/src/java/org/apache/commons/logging/impl/WeakHashtable.java b/optional/src/java/org/apache/commons/logging/impl/WeakHashtable.java index 99c4309..a1ac64b 100644 --- a/optional/src/java/org/apache/commons/logging/impl/WeakHashtable.java +++ b/optional/src/java/org/apache/commons/logging/impl/WeakHashtable.java @@ -23,6 +23,8 @@ import java.util.*; /** *

Implementation of Hashtable that uses WeakReference's * to hold it's keys thus allowing them to be reclaimed by the garbage collector. + * This class follows the symantics of Hashtable as closely as possible. + * It therefore does not accept null values or keys. *

*

* Usage: typical use case is as a drop-in replacement @@ -152,6 +154,14 @@ public final class WeakHashtable extends Hashtable { *@see Hashtable */ public Object put(Object key, Object value) { + // check for nulls, ensuring symantics match superclass + if (key == null) { + throw new NullPointerException("Null keys are not allowed"); + } + if (value == null) { + throw new NullPointerException("Null values are not allowed"); + } + Object result = null; Referenced lastValue = (Referenced) super.put(new Referenced(key), new Referenced(value)); if (lastValue != null) { diff --git a/optional/src/test/org/apache/commons/logging/impl/WeakHashtableTest.java b/optional/src/test/org/apache/commons/logging/impl/WeakHashtableTest.java index 23ee252..f5c8e98 100644 --- a/optional/src/test/org/apache/commons/logging/impl/WeakHashtableTest.java +++ b/optional/src/test/org/apache/commons/logging/impl/WeakHashtableTest.java @@ -153,6 +153,24 @@ public class WeakHashtableTest extends TestCase { weakHashtable.put(anotherKey, new Long(1066)); assertEquals(new Long(1066), weakHashtable.get(anotherKey)); + + // Test compliance with the hashtable API re nulls + Exception caught = null; + try { + weakHashtable.put(null, new Object()); + } + catch (Exception e) { + caught = e; + } + assertNotNull("did not throw an exception adding a null key", caught); + caught = null; + try { + weakHashtable.put(new Object(), null); + } + catch (Exception e) { + caught = e; + } + assertNotNull("did not throw an exception adding a null value", caught); } /** Tests public void putAll(MapÊt) */