构建具有继承的通用树

2024-04-09

我正在构建一个通用的Tree<T>类,支持子树的继承。但我遇到了一些问题。请您帮帮我好吗?

描述

让我们定义Tree类和BlueTree班级,哪里BlueTree extends Tree.

让我们定义Leaf类和RedLeaf班级,哪里RedLeaf extends Leaf。它们被用作树包含的“数据”。

A Tree<Leaf>表示类型为 TreeTree,其“数据”类型为Leaf.

为了继承(这是not正确的 Java 继承):

  • a Tree<Leaf> can have child of type
    • Tree<Leaf>, Tree<RedLeaf>, BlueTree<Leaf>, and BlueTree<RedLeaf>.

.

  • a Tree<RedLeaf> can have child of type
    • Tree<RedLeaf>, and BlueTree<RedLeaf>,
    • but not Tree<Leaf>, or BlueTree<Leaf>.

.

  • a BlueTree<Leaf> can have child of type
    • BlueTree<Leaf>, and BlueTree<RedLeaf>,
    • but not Tree<Leaf>, or Tree<RedLeaf>.

.

  • a BlueTree<RedLeaf> can have child of type
    • BlueTree<RedLeaf>,
    • but not Tree<Leaf>, Tree<RedLeaf>, or BlueTree<Leaf>.

*这里,“孩子”是指树的树枝/叶子。

(有点复杂,这就是我分开线条的原因。)

The code

(如果你有解决方案,你可能不需要阅读下面我尝试的详细说明。如果你想一起找出解决方案,我的代码可能会给你一些想法 - 或者,它可能会让他们感到困惑。)

一审:(最简单的)

// This is the focus of this question, the class signature
public class Tree<T> {
    // some fields, but they are not important in this question
    private Tree<? super T> mParent;
    private T mData;
    private ArrayList<Tree<? extends T>> mChildren;

    // This is the focus of this question, the addChild() method signature
    public void addChild(final Tree<? extends T> subTree) {
        // add the subTree to mChildren
    }
}

该类结构满足描述中的大部分要求。除了,它允许

class BlueTree<T> extends Tree<T> { }
class Leaf { }
class RedLeaf extends Leaf { }

Tree<Leaf> tree_leaf = new Tree<Leaf>();
BlueTree<Leaf> blueTree_leaf = new BlueTree<Leaf>();

blueTree_leaf.addChild(tree_leaf);    // should be forbidden

这违反了

  • a BlueTree<Leaf> cannot有类型的孩子Tree<Leaf>.

问题是因为,在BlueTree<Leaf>, its addChild()方法签名仍然是

public void addChild(final Tree<? extends Leaf> subTree) {
     // add the subTree to mChildren
}

理想的情况是,BlueTree<Leaf>.addChild()方法签名更改(继承时自动)为

public void addChild(final BlueTree<? extends Leaf> subTree) {
     // add the subTree to mChildren
}

(注意这个方法cannot由于参数类型不同,通过继承重写上述方法。)

有一个解决方法。我们可以添加一个类继承检查,并抛出RuntimeException对于这种情况:

public void addChild(final Tree<? extends Leaf> subTree) {
    if (this.getClass().isAssignableFrom(subTree.getClass()))
        throw new RuntimeException("The parameter is of invalid class.");
    // add the subTree to mChildren
}

但使其成为编译时错误比运行时错误要好得多。我想在编译时强制执行此行为。

二审

第一个试验结构的问题是,参数类型Tree在方法中addChild()不是泛型类型参数。因此它不会在继承时更新。这次,我们也尝试将其设为泛型类型参数。

首先定义一下一般情况Tree class.

public class Tree<T> {
    private Tree<? super T> mParent;
    private T mData;
    private ArrayList<Tree<? extends T>> mChildren;

    /*package*/ void addChild(final Tree<? extends T> subTree) {
        // add the subTree to mChildren
    }
}

然后TreeManager它管理着一个Tree object.

public final class TreeManager<NodeType extends Tree<? super DataType>, DataType> {
    private NodeType mTree;

    public TreeManager(Class<NodeType> ClassNodeType) {
        try {
            mTree = ClassNodeType.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void managerAddChild(final NodeType subTree) {
        mTree.addChild(subTree);
        // compile error: The method addChild(Tree<? extends capture#1-of ? super DataType>)
        //                in the type Tree<capture#1-of ? super DataType>
        //                is not applicable for the arguments (NodeType)
    }

    // for testing
    public static void main(String[] args) {
        @SuppressWarnings("unchecked")
        TreeManager<Tree    <Leaf>   , Leaf>    tm_TreeLeaf_Leaf           = new TreeManager<Tree    <Leaf>,    Leaf>   ((Class<Tree    <Leaf>>)    new Tree    <Leaf>   ().getClass());
        TreeManager<Tree    <RedLeaf>, RedLeaf> tm_TreeRedLeaf_RedLeaf     = new TreeManager<Tree    <RedLeaf>, RedLeaf>((Class<Tree    <RedLeaf>>) new Tree    <RedLeaf>().getClass());
        TreeManager<BlueTree<Leaf>   , Leaf>    tm_BlueTreeLeaf_Leaf       = new TreeManager<BlueTree<Leaf>,    Leaf>   ((Class<BlueTree<Leaf>>)    new BlueTree<Leaf>   ().getClass());
        TreeManager<BlueTree<RedLeaf>, RedLeaf> tm_BlueTreeRedLeaf_RedLeaf = new TreeManager<BlueTree<RedLeaf>, RedLeaf>((Class<BlueTree<RedLeaf>>) new BlueTree<RedLeaf>().getClass());

        System.out.println(tm_TreeLeaf_Leaf          .mTree.getClass());    // class Tree
        System.out.println(tm_TreeRedLeaf_RedLeaf    .mTree.getClass());    // class Tree
        System.out.println(tm_BlueTreeLeaf_Leaf      .mTree.getClass());    // class BlueTree
        System.out.println(tm_BlueTreeRedLeaf_RedLeaf.mTree.getClass());    // class BlueTree

        @SuppressWarnings("unchecked")
        TreeManager<Tree    <Leaf>   , RedLeaf> tm_TreeLeaf_RedLeaf     = new TreeManager<Tree    <Leaf>,    RedLeaf>((Class<Tree    <Leaf>>)    new Tree    <Leaf>   ().getClass());
        TreeManager<BlueTree<Leaf>   , RedLeaf> tm_BlueTreeLeaf_RedLeaf = new TreeManager<BlueTree<Leaf>,    RedLeaf>((Class<BlueTree<Leaf>>)    new BlueTree<Leaf>   ().getClass());

        System.out.println(tm_TreeLeaf_RedLeaf       .mTree.getClass());    // class Tree
        System.out.println(tm_BlueTreeLeaf_RedLeaf   .mTree.getClass());    // class BlueTree

        // the following two have compile errors, which is good and expected.
        TreeManager<Tree    <RedLeaf>, Leaf>    tm_TreeRedLeaf_Leaf     = new TreeManager<Tree    <RedLeaf>, Leaf>   ((Class<Tree    <RedLeaf>>) new Tree    <RedLeaf>().getClass());
        TreeManager<BlueTree<RedLeaf>, Leaf>    tm_BlueTreeRedLeaf_Leaf = new TreeManager<BlueTree<RedLeaf>, Leaf>   ((Class<BlueTree<RedLeaf>>) new BlueTree<RedLeaf>().getClass());
    }
}

The TreeManager初始化没有问题;不过队伍有点长。它也符合描述中的规则。

但是调用时出现编译错误Tree.addChild() inside TreeManager,如上图所示。

第三次审判

为了修复第二次试验中的编译错误,我尝试更改类签名(甚至更长)。现在mTree.addChild(subTree);编译没有问题。

// T is not used in the class. T is act as a reference in the signature only
public class TreeManager3<T, NodeType extends Tree<T>, DataType extends T> {
    private NodeType mTree;

    public TreeManager3(Class<NodeType> ClassNodeType) {
        try {
            mTree = ClassNodeType.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void managerAddChild(final NodeType subTree) {
        mTree.addChild(subTree);    // compile-error is gone
    }
}

我已经使用与第二次试验非常相似的代码对其进行了测试。它创建时没有任何问题,就像第二次试验一样。 (甚至更长。)

(您可以跳过下面的代码块,因为它只是逻辑上的重复。)

public static void main(String[] args) {
    @SuppressWarnings("unchecked")
    TreeManager3<Leaf   , Tree    <Leaf>   , Leaf>    tm_TreeLeaf_Leaf           = new TreeManager3<Leaf   , Tree    <Leaf>,    Leaf>   ((Class<Tree    <Leaf>>)    new Tree    <Leaf>   ().getClass());
    TreeManager3<RedLeaf, Tree    <RedLeaf>, RedLeaf> tm_TreeRedLeaf_RedLeaf     = new TreeManager3<RedLeaf, Tree    <RedLeaf>, RedLeaf>((Class<Tree    <RedLeaf>>) new Tree    <RedLeaf>().getClass());
    TreeManager3<Leaf   , BlueTree<Leaf>   , Leaf>    tm_BlueTreeLeaf_Leaf       = new TreeManager3<Leaf   , BlueTree<Leaf>,    Leaf>   ((Class<BlueTree<Leaf>>)    new BlueTree<Leaf>   ().getClass());
    TreeManager3<RedLeaf, BlueTree<RedLeaf>, RedLeaf> tm_BlueTreeRedLeaf_RedLeaf = new TreeManager3<RedLeaf, BlueTree<RedLeaf>, RedLeaf>((Class<BlueTree<RedLeaf>>) new BlueTree<RedLeaf>().getClass());

    System.out.println(tm_TreeLeaf_Leaf          .mTree.getClass());    // class Tree
    System.out.println(tm_TreeRedLeaf_RedLeaf    .mTree.getClass());    // class Tree
    System.out.println(tm_BlueTreeLeaf_Leaf      .mTree.getClass());    // class BlueTree
    System.out.println(tm_BlueTreeRedLeaf_RedLeaf.mTree.getClass());    // class BlueTree

    @SuppressWarnings("unchecked")
    TreeManager3<Leaf   , Tree    <Leaf>   , RedLeaf> tm_TreeLeaf_RedLeaf     = new TreeManager3<Leaf   , Tree    <Leaf>,    RedLeaf>((Class<Tree    <Leaf>>)    new Tree    <Leaf>   ().getClass());
    TreeManager3<Leaf   , BlueTree<Leaf>   , RedLeaf> tm_BlueTreeLeaf_RedLeaf = new TreeManager3<Leaf   , BlueTree<Leaf>,    RedLeaf>((Class<BlueTree<Leaf>>)    new BlueTree<Leaf>   ().getClass());

    System.out.println(tm_TreeLeaf_RedLeaf       .mTree.getClass());    // class Tree
    System.out.println(tm_BlueTreeLeaf_RedLeaf   .mTree.getClass());    // class BlueTree

    // the following two have compile errors, which is good and expected.
    TreeManager3<RedLeaf, Tree    <RedLeaf>, Leaf>    tm_TreeRedLeaf_Leaf     = new TreeManager3<RedLeaf, Tree    <RedLeaf>, Leaf>   ((Class<Tree    <RedLeaf>>) new Tree    <RedLeaf>().getClass());
    TreeManager3<RedLeaf, BlueTree<RedLeaf>, Leaf>    tm_BlueTreeRedLeaf_Leaf = new TreeManager3<RedLeaf, BlueTree<RedLeaf>, Leaf>   ((Class<BlueTree<RedLeaf>>) new BlueTree<RedLeaf>().getClass());
}

但是,当我尝试致电时出现问题TreeManager3.managerAddChild().

tm_TreeLeaf_Leaf.managerAddChild(new Tree<Leaf>());
tm_TreeLeaf_Leaf.managerAddChild(new Tree<RedLeaf>());      // compile error: managerAddChild(Tree<RedLeaf>) cannot cast to managerAddChild(Tree<Leaf>)
tm_TreeLeaf_Leaf.managerAddChild(new BlueTree<Leaf>());
tm_TreeLeaf_Leaf.managerAddChild(new BlueTree<RedLeaf>());  // compile error: managerAddChild(BlueTree<RedLeaf>) cannot cast to managerAddChild(BlueTree<Leaf>)

这是可以理解的。TreeManager3.managerAddChild(NodeType) means TreeManager3.managerAddChild(Tree<T>)并且没有通配符Tree<? extends T>在参数类型中,例如Tree.addChild(final Tree<? extends T> subTree)在第一次审判中。

恳求你的帮助...

我已经没有想法了。我解决这个问题的方向是错误的吗?我花了很多时间来输入这个问题,并尽最大努力使其更具可读性、更容易理解和遵循。我不得不说抱歉,它仍然很长而且冗长。但是如果您知道路的话可以帮忙吗,或者请给我您的任何想法吗?我们非常感谢您的每一次投入。多谢!


编辑#1(对于下面评论 https://stackoverflow.com/questions/18399922/build-a-generic-tree-with-inheritance#comment27433242_18399922)

总部设在一审, 只允许mChildren修改为addChild()(以及其他方法isAssignableFrom()检查),所以即使允许用户继承Tree并压倒一切addChild()不会破坏树的完整性。

/developer/util/Tree.java

package developer.util;

import java.util.ArrayList;

public class Tree<T> {

    private Tree<? super T> mParent;
    private final ArrayList<Tree<? extends T>> mChildren = new ArrayList<Tree<? extends T>>();

    public int getChildCount() { return mChildren.size(); }
    public Tree<? extends T> getLastChild() { return mChildren.get(getChildCount()-1); }

    public void addChild(final Tree<? extends T> subTree) {
        if (this.getClass().isAssignableFrom(subTree.getClass()) == false)
            throw new RuntimeException("The child (subTree) must be a sub-class of this Tree.");

        subTree.mParent = this;
        mChildren.add(subTree);
    }
}

/用户/pkg/BinaryTree.java

package user.pkg;

import developer.util.Tree;

public class BinaryTree<T> extends Tree<T> {
    @Override
    public void addChild(final Tree<? extends T> subTree) {
        if (getChildCount() < 2) {
            super.addChild(subTree);
        }
    }
}

/Main.java

import user.pkg.BinaryTree;
import developer.util.Tree;

public class Main {

    public static void main(String[] args) {
        Tree<Integer> treeOfInt = new Tree<Integer>();
        BinaryTree<Integer> btreeOfInt = new BinaryTree<Integer>();

        treeOfInt.addChild(btreeOfInt);
        System.out.println(treeOfInt.getLastChild().getClass());
        // class user.pkg.BinaryTree

        try {
            btreeOfInt.addChild(treeOfInt);
        } catch (Exception e) {
            System.out.println(e);
            // java.lang.RuntimeException: The child (subTree) must be a sub-class of this Tree.
        }

        System.out.println("done.");
    }
}

你怎么认为?


在我看来,这个问题没有完美的解决方案。这基本上是由于类型擦除造成的。这删除通用方法 http://docs.oracle.com/javase/tutorial/java/generics/genMethods.html文章解释说你的addChild(final Tree<? extends Leaf> subTree)函数将变成addChild(final Tree subTree)功能。所以,即使你可以以某种方式拥有一个通用参数<TreeType extends Tree<? extends Leaf>> addChild(final TreeType subTree)(无效语法!)它将被删除addChild(final Tree subTree)在编译时。不过,添加运行时测试将会起作用,因此您所做的编辑将完成这项工作。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

构建具有继承的通用树 的相关文章

  • string.split("(?!^)") 解释

    我正在尝试将字符串的字符拆分为字符串数组 我找到了解决方案here https stackoverflow com questions 5235401 split string into array of character strings
  • Google App Engine 数据存储写入:如何远程启用/禁用只读模式?

    在阅读备份时GAE 的数据存储 https developers google com appengine docs adminconsole datastoreadmin where 我们强烈建议您在备份或恢复期间将应用程序设置为只读模式
  • 将键与多个值对象关联的有效集合[重复]

    这个问题在这里已经有答案了 有任何有效的集合可以将键与多个值关联起来 例如 new HashMap
  • 如何访问EmbeddedSolrServer实例的管理界面?

    在我的网络应用程序中 我正在运行org apache solr client solrj embedded EmbeddedSolrServer出于调试目的 我想访问管理界面 这就是我实例化服务器的方式 new EmbeddedSolrSe
  • Java:等于和==

    让我们看看我们有 2 个对用户定义类实例的引用 即 Java 中的 a 和 b 会不会有一种情况 a b 但 a equals b 返回 false 当然 实施 equals 完全取决于班级 所以我可以写 class Foo public
  • 参考接口创建对象

    引用变量可以声明为类类型或接口类型 如果变量声明为接口类型 则它可以引用实现该接口的任何类的任何对象 根据上面的说法我做了一个理解上的代码 正如上面所说声明为接口类型 它可以引用实现该接口的任何类的任何对象 但在我的代码中显示display
  • Mockito mockStatic 无法解析符号

    我正在使用 Spring Boot 并在单元测试中 我试图模拟Files delete myFile toPath method 为此 我尝试使用Mockito mockStatic 方法 但是当我尝试使用它时 我的 IDE Intelli
  • python 中的子进程调用以使用 JAVA_OPTS 调用 java jar 文件

    示例代码 import subprocess subprocess call java jar temp jar 如何在上面的命令中指定JAVA OPTS 当我使用上述命令时 我收到 java lang OutOfMemoryError 无
  • Spark SQL 失败,因为“常量池已超过 JVM 限制 0xFFFF”

    我在 EMR 4 6 0 Spark 1 6 1 上运行此代码 val sqlContext SQLContext getOrCreate sc val inputRDD sqlContext read json input try inp
  • Java:从 ScriptEngine javascript 返回一个对象

    我正在尝试使用 Java 来评估 javascript脚本引擎 https docs oracle com javase 7 docs api javax script ScriptEngine html班级 这是我正在尝试做的事情的一个简
  • 加密 mongodb 中的密码字段

    我有以下代码 它插入userName and password进入数据库 但密码以纯文本格式存储 我的意思是 当我查看数据库时 我可以看到插入的密码 我想存储password in encrypted format MongoClient
  • 如何在 PuTTY 中保存并运行 Java 文件?

    我是 AWS 亚马逊网络服务 的新手 所以这可能是一个基本问题 我在 AWS 上创建了一个 EC2 实例 我有一台 Windows 计算机 因此我使用 PUTTY 来连接 Linux 实例 连接到我的 EC2 实例后 我使用以下命令编写 J
  • Java MYSQL/JDBC 查询从缓存的连接返回过时的数据

    我一直在 Stackoverflow 中寻找答案 但似乎找不到不涉及 Hibernate 或其他数据库包装器的答案 我直接通过 Tomcat 6 Java EE 应用程序中的 MYSQL 5 18 JDBC 驱动程序使用 JDBC 我正在缓
  • 从 Java 应用程序读取的文件是否会调用系统调用?

    我的理解是 请求文件系统路径 例如 aFile 的用户应用程序将调用文件系统并获取所请求文件的虚拟地址 然后应用程序将尝试以该地址作为参数 即作为 CPU 指令 进行读 写操作 执行读取命令时 内存管理单元会将该地址转换为物理地址 并查看页
  • 在进行堆转储后,如何在发生 OutOfMemoryError 时重新启动 JVM?

    我知道关于 XX HeapDumpOnOutOfMemoryError https stackoverflow com q 542979 260805JVM 参数 我也知道 XX OnOutOfMemoryError cmd args cm
  • Spring Data MongoDB 和批量更新

    我正在使用 Spring Data MongoDB 并且想要执行批量更新 就像此处描述的那样 http docs mongodb org manual reference method Bulk find update Bulk find
  • “mvn”不被识别为内部或外部命令、可操作程序或批处理文件

    可能是之前问过问题 但我发现了非常奇怪的错误 当我跑步时mvn versionbin 中的命令给出了版本和其他信息 但是 当我跑到垃圾箱外面时 它会出现异常 下面提到的结果 C Program Files apache maven 3 0
  • 什么是多重重继承?

    我将以下称为 多重重新继承 直接继承一个类一次 并通过继承其一个或多个后代来间接继承一次或多次 通过继承一个类的两个或多个后代来间接继承一个类两次或多次 我想知道它是否存在以及如何明确访问嵌入的子对象 1 Professional C 2n
  • Bipush 在 JVM 中如何工作?

    我知道 iload 接受整数 1 到 5 但是如何使用 bipush 指令扩展到更高的数字 特定整数如何与字节码一起存储 有几种不同的指令可用于推送整数常量 最小的是iconst 指令 这些只是一个字节 因为该值是在操作码本身中编码的 ic
  • Selenium Webdriver - 单击多个下拉菜单时出现陈旧元素异常,而 HTML DOM 不会更改

    我尝试自动化一个场景 其中条件是我必须从下拉列表中选择一个选项 然后它旁边有另一个下拉列表 我必须单击下一个下拉列表中的一个选项才能启用按钮 我尝试使用代码 但它仅单击第一个选项 并显示错误为过时的元素引用 元素未附加到页面文档 请帮忙 如

随机推荐