[英]How do I merge both of these functions together?
public boolean insert(K key, V value) {
if (contains(key)) { //if the binary tree contains it don't insert it.
return false;
}
if (rNode == null) { //if the root node is empty, there is nothing in the tree
//create a new DictionaryNode.
rNode = new DictionaryNode<K, V>(key, value);
curNode = rNode;
} else {//if the above aren't true then you can insert it.
placeNode(key, value, rNode, null, false); //use private method placeNode
}
changeCounter++;
currentSize++;
return true;
}//end insert
这是另一个功能。 我希望能够在我的insert方法中执行placeNode的所有操作。 我希望能够摆脱我的placeNode方法。
private void placeNode(K key, V value, DictionaryNode<K, V> node, DictionaryNode<K, V> parent, boolean nodeLeft) {
if (node == null) {
if (nodeLeft) {
parent.lChild = new DictionaryNode<K, V>(key, value);
} else {
parent.rChild = new DictionaryNode<K, V>(key, value);
}
} else if (((Comparable<K>) key).compareTo(node.key) < 0) {
placeNode(key, value, node.lChild, node, true);
} else {
placeNode(key, value, node.rChild, node, false);
}
}//end placeNode
除了将这两个功能合并在一起令人头疼之外, 没有任何收获。 它们执行不同的操作,因此,应尽可能将其分成较小的代码块。
方法的划分很好 。 不要试图合并它们。
您唯一能做的就是用您要删除的方法的确切主体替换您的方法调用,但这会使事情变得极其复杂。
((Comparable<K>) key
一句,您的强制转换((Comparable<K>) key
可能会产生ClassCastException
。如果绑定到K
的类型不具有可比性,那么在运行时 ,您将遇到一个主要问题。这种方式-您想提供类型的编译时安全性。
幸运的是,您可以通过在类中添加类型的上限来解决此问题:
public class DictionaryNode<K extends Comparable<K>, V> {
// implementation to follow
}
private DictionaryNode<K, V> curNode = rNode;
public boolean insert(K key, V value) {
if (contains(key)) { // if the binary tree contains it don't insert it.
return false;
}
if (rNode == null) { // if the root node is empty, there is nothing in
// the tree
// create a new DictionaryNode.
rNode = new DictionaryNode<K, V>(key, value);
} else {// if the above aren't true then you can insert it.
int c = ((Comparable<K>)key).compareTo(curNode.key);
if (c < 0) {
if (curNode.lChild == null) {
curNode.lChild = new DictionaryNode<K, V>(key, value);
}
else {
curNode = curNode.lChild;
return insert(key, value);
}
}
else {
if (curNode.rChild == null) {
curNode.rChild = new DictionaryNode<K, V>(key, value);
}
else {
curNode = curNode.rChild;
return insert(key, value);
}
}
}
curNode = rNode;
changeCounter++;
currentSize++;
return true;
}
编辑-
假设K和V来自类声明,则应将它们声明为
public SomeClass<K extends Comparable<K>, V extends Comparable<V> { ... }
正如诚人所建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.