[英]How to avoid casting on inherited recursive class with wildcard?
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();
我对铸造不过敏,但在这种情况下非常重。 提前感谢您的回答!
您可以使用更多的泛型,即CRTP :
abstract class AbstractBinaryTree<T, TTree extends AbstractBinaryTree<T, TTree>> {
TTree parent;
TTree leftChild;
TTree rightChild;
T value;
}
而不是具有抽象超类的类引用自身对树结构的引用,我会让它使用一个Node
类,它引用了它的父Node
,以及左右子Nodes
。 该AbstractBinaryTree
类必须根参考Node
。
abstract class AbstractBinaryTree<T> {
Node<T> root;
static class Node<E>
{
Node<E> parent;
Node<E> leftChild;
Node<E> rightChild;
E value;
}
}
那么子类不需要Node
的类型随其自己的类型而变化; BinarySearchTree
也将使用Node
。
class BinarySearchTree<T extends Comparable<T>> extends AbstractBinaryTree<T>
{
// No need to redefine the structure types here.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.