Stop blowing up on a null key, but rather return that the element is not found.

This commit is contained in:
Joel Leitch 2013-01-09 23:37:38 +00:00
parent b0531e1649
commit 3f2efac95e
2 changed files with 28 additions and 8 deletions

View File

@ -387,14 +387,16 @@ public class LinkedTreeMap<K extends Comparable<K>, V>
}
private TreeNode<K, V> find(K key) {
for (TreeNode<K, V> entry = root; entry != null; ) {
int compareVal = key.compareTo(entry.key);
if (compareVal < 0) {
entry = entry.left;
} else if (compareVal > 0) {
entry = entry.right;
} else {
return entry;
if (key != null) {
for (TreeNode<K, V> entry = root; entry != null; ) {
int compareVal = key.compareTo(entry.key);
if (compareVal < 0) {
entry = entry.left;
} else if (compareVal > 0) {
entry = entry.right;
} else {
return entry;
}
}
}
return null;

View File

@ -56,6 +56,24 @@ public class LinkedTreeMapTest extends TestCase {
assertEquals(map.size(), map.entrySet().size());
}
public void testGetAndContainsNullKey() throws Exception {
LinkedTreeMap<String, Integer> map = new LinkedTreeMap<String, Integer>();
assertFalse(map.containsKey(null));
assertNull(map.get(null));
map.put("A", 1);
assertFalse(map.containsKey(null));
assertNull(map.get(null));
}
public void testDisallowPutForNullKeys() throws Exception {
LinkedTreeMap<String, Integer> map = new LinkedTreeMap<String, Integer>();
try {
map.put(null, 1);
fail();
} catch (NullPointerException expected) {}
}
public void testSingleElement() throws Exception {
LinkedTreeMap<String, Integer> map = new LinkedTreeMap<String, Integer>();
map.put("A", 1);