gpt4 book ai didi

java - 如何避免使用通配符对继承的递归类进行强制转换?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:12:12 26 4
gpt4 key购买 nike

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;
}
}

如何避免强制转换所有左 child 和右 child ?

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;
}

或者当我给 child 打电话时?

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;
}

关于java - 如何避免使用通配符对继承的递归类进行强制转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26184075/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com