[英]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.