1)假设你有以下的抽象类定义:如何避免使用通配符继承性递归类转换?
abstract class AbstractBinaryTree<T> {
AbstractBinaryTree<T> parent;
AbstractBinaryTree<T> leftChild;
AbstractBinaryTree<T> rightChild;
T value;
}
和本类与以前没有申报或实施了新的方法实现:
public class BinarySearchTree<T extends Comparable<T>> extends AbstractBinaryTree<T> {
public BinarySearchTree(T pVal) {
super(pVal);
}
public Boolean isBST(){
if(leftChild != null && rightChild != null){
return (leftChild.value.compareTo(value) < 0
&& rightChild.value.compareTo(value) >= 0)
&& ((BinarySearchTree<T>) leftChild).isBST()
&& ((BinarySearchTree<T>) rightChild).isBST();
}
else if(leftChild != null){
return leftChild.value.compareTo(value) < 0
&& ((BinarySearchTree<T>) leftChild).isBST() ;
}
else if (rightChild != null){
return rightChild.value.compareTo(value) >= 0
&& ((BinarySearchTree<T>) rightChild).isBST();
}
else{
return true;
}
}
你如何避免投所有的左右儿童?
2)同样假设我在AbstractBinaryTree以下抽象定义:
public abstract AbstractBinaryTree<T> findMinTree();
及其在BST实现:
/***
* @return the subtree rooted at the min value
*/
public BinarySearchTree<T> findMinTree(){
if(leftChild != null)
return (BinarySearchTree<T>) leftChild.findMinTree();
return this;
}
如何避免在
public BinarySearchTree<T> findMinTree(){
if(leftChild != null)
return (BinarySearchTree<T>) leftChild.findMinTree();
return this;
}
投
或者当我给小孩打电话时?
BinarySearchTree<T> y = ((BinarySearchTree<T>) x.rightChild).findMinTree();
我对铸造不过敏,但在这种情况下它非常沉重。 在此先感谢您的答案!
作为一个完全切评论,你会想在'isBST返回'boolean',而不是'Boolean'( )'方法 - 就像它将你的返回值自动装箱到'Boolean'对象中,这可能不是你想要的。 – Krease 2014-10-03 17:53:31