[英]Put method of a TreeMap implementation
I'm working on an implementation of TreeMap(called MyTreeMap) and I'm having a lot of trouble with the put method. 我正在开发TreeMap(称为MyTreeMap)的实现,但是put方法遇到了很多麻烦。 I was hoping someone could look at my code and point me in the right direction as to where things start to go wrong.
我希望有人可以查看我的代码,并向我指出发生错误的正确方向。
public class MyTreeMap<K extends Comparable<? super K>,V> extends AbstractMap<K,V> {
K key;
V value;
int height;
MyTreeMap<K,V> left,right;
int size;
public V put(K key, V value) {
int compareValue = this.key.compareTo(key);
if(!this.containsKey(key)) {
if(this.key == null) {
this.key = key;
this.value = value;
}
if(this.isLeaf() || this.isEmpty()) {
if(this.key.compareTo(key) > 0)
this.left = new MyTreeMap<K,V>(key,value,null,null);
else
this.right = new MyTreeMap<K,V>(key,value,null,null);
if(left.height > right.height + 1 || right.height > left.height + 1)
restructure(this);
this.size++;
setHeight();
return null;
}
else {
if(compareValue > 0)
return this.left.put(key, value);
else
return this.right.put(key, value);
}
}
else {
if(compareValue == 0) {
V temp = this.value;
this.value = value;
return temp;
}
else if(compareValue < 0)
return this.right.put(key, value);
else
return this.left.put(key, value);
}
}
I think your logic is a bit inside-out, and as a result is a lot more complicated than it needs to be: the top level if
should probably be looking at the compareValue
, not doing the containsKey
check. 我认为您的逻辑有点由内而外,结果比所需的要复杂得多:顶层
if
应该查看compareValue
,而不是执行containsKey
检查。
Logic should be: 逻辑应为:
compareValue==0
then this means you have found the right key, so just update the value and return compareValue==0
则意味着您找到了正确的键,因此只需更新值并返回 PS I suggest not allowing null keys in a TreeMap, it will make your life simpler, and will avoid the need to do null checks on keys PS:我建议在TreeMap中不允许使用空键,这会使您的生活更简单,并且避免对键进行空值检查
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.