【发布时间】:2020-09-15 08:40:09
【问题描述】:
目前,我正在开展一个项目,我正在从头开始实现链接字典接口。一切都很顺利,直到我意识到我的代码一旦看到一个空值就声称整个字典都是空的。
public class LinkedDictionary<K, V> implements Dictionary<K, V> {
/** List node. */
private class Node {
K key;
V value;
Node next;
Node(K key, V value, Node next) {
this.key = key;
this.value = value;
this.next = next;
}
}
/** The first node in this dictionary, or null if this dictionary is empty. */
private Node front;
@Override
public void put(K key, V value) {
if(value == null) { // if a null value is given, the dictionary is empty
isEmpty();
return;
}
for (Node n = front; n != null; n = n.next) {
if (n.key.equals(key)) {
return;
}
}
front = new Node(key, value, front); // front node now contains new key and value
}
@Override
public V get(K key) {
if (key == null) // if a null key is given, null is returned
return null;
for (Node n = front; n != null; n = n.next) {
if (n.key.equals(key)) {
return n.value; // if they key is within the contents of the dictionary, return the corresponding value
}
}
return null; //if the key does not appear in the dictionary, null is returned.
}
@Override
public boolean isEmpty() {
return front == null;
}
}
我很清楚地看到了我的问题。在我的“put”方法中,如果用户尝试输入一个空值,整个字典将被标记为“空”。 我在想象这种情况:
Dictionary<Integer, String> d = new LinkedDictionary<>();
d.put(1, "one");
d.put(2, "two");
d.put(1, null);
一旦我的实现到达键 1 设置为 null 的第三行,它将把整个字典设置为空,尽管事实上键 2 处仍有一个有效条目。 我一直在绞尽脑汁思考如何更改我的代码以允许出现这种情况,但我无法弄清楚。我尝试改变我的 isEmpty 方法,甚至尝试添加一个额外的方法,但我似乎不知道该怎么做!
任何指向正确方向的指针或推动将不胜感激!
【问题讨论】:
-
嗯,
isEmpty()作为一个独立的表达式有点奇怪。 -
所以如果我理解正确的话,你想让
isEmpty()在d.put(1, null);被执行之后为真吗?那是一本奇怪的字典…… -
最后一行应该发生什么?将键 1 的值更改为 null ?我看不出你把字典放在哪里了。您对
isEmpty()的调用不会改变前面,它只会检查它是否为空。 -
它为我返回
false...你能显示minimal reproducible example吗? -
front 永远不会设置为 null,因此一旦将第一个 Node 放入其中,它将永远不会再为空。
标签: java dictionary