我目前正在做一项作业,要求我在 Java 中创建一个 Map 类,并且在使用“put”方法时遇到了一个错误,我似乎无法修复该错误。本质上,当测试运行时, map 中的新节点将不会被创建,我似乎无法弄清楚为什么。预先感谢您!
类(class):
public class MyMap<K extends Comparable<K>, V> {
private class MapNode {
private K key;
private V value;
private MapNode left;
private MapNode right;
public MapNode(K theKey, V theValue) {
key = theKey;
value = theValue;
left = null;
right = null;
}
}
private MapNode root;
public MyMap() {
root = null;
}
/**
* Associates key to value and stores mapping If key exists, replaces value
* with a new value
*
* @param key
* @param value
* @return value replaced; null if no value
*/
public V put(K key, V value) {
return put(key, value, root);
}
private V put(K key, V value, MapNode ref) {
V temp;
if (ref == null) {
ref = new MapNode(key, value);
return null;
} else {
if (ref.key.compareTo(key) == 0) {
temp = ref.value;
ref.value = value;
return temp;
} else if (key.compareTo(ref.key) < 0)
return put(key, value, ref.left);
else
return put(key, value, ref.right);
}
}
/**
* Return value to which key is mapped
*
* @param key
* @return value of key; null
*/
public V get(K key) {
return get(key, root);
}
private V get(K key, MapNode ref) {
if (ref == null) {
return null;
} else {
if (ref.key.compareTo(key) == 0)
return ref.value;
else if (key.compareTo(ref.key) < 0)
return get(key, ref.left);
else if (key.compareTo(ref.key) > 0)
return get(key, ref.right);
else
return null;
}
}
/**
* Returns true if Map already uses the key
*
* @param key
* @return true; false
*/
public boolean containsKey(K key) {
return containsKey(key, root);
}
private boolean containsKey(K key, MapNode ref) {
if (ref == null) {
return false;
} else {
if (ref.key.compareTo(key) == 0)
return true;
else if (key.compareTo(ref.key) < 0)
return containsKey(key, ref.left);
else if (key.compareTo(ref.key) > 0)
return containsKey(key, ref.right);
else
return false;
}
}
}
测试:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class MyMapTest {
@Test
public void testMyMap(){
MyMap<String, Integer> m = new MyMap<String, Integer>();
assertFalse(m.containsKey("one"));
assertEquals(null, m.get("one"));
assertEquals(null, m.put("one", 1));
assertTrue(m.containsKey("one"));
}
}
最佳答案
在 put(K key, V value, MapNode ref)
方法中,您将一个新的 MapNode 分配给包含要添加的节点的 ref
。
我看到您通过传递root
来调用该方法。这会存储 与 ref
中 root
中存储的相同引用。这意味着,如果 root
不为空。但是,由于 root
为 null
,因此它们都指向 null
。
当您分配ref = new MapNode(key, value);
时,您将ref
指向新节点,但root
仍然指向为空。
您需要将 root
指向新的 MapNode,将 ref
指向它并不适合您。
关于java - 用 Java 实现 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10235996/