【问题标题】:Java Class that iterates its own type when extended扩展时迭代其自身类型的 Java 类
【发布时间】:2016-05-08 00:07:54
【问题描述】:

我想创建一个只有节点的自定义树数据结构,我可以在其中迭代它们。然后,我以后可以扩展这个类并拥有非常基本的树

class Node{

    Node parent;
    ArrayList<Node> children;

    public static void main(String[]args){
        Node root = new Node();
        for(Node child : root){
            //do something
        }
    }

    public Iterator<Node> iterator(){
        // basic tree traversal iterator
    }  
}

我已经让它工作了,但是当我尝试扩展 Node 类时问题就来了。对于扩展类,继承的迭代器方法仍然返回 Node 迭代器,这意味着我每次都必须进行强制转换。这是我遇到的问题的一个基本示例。让我们创建一个包含整数的树:

class IntegerNode extends Node{

    int value;

    public static void main(String[]args){

        IntegerNode root = new IntegerNode();
        int total = 0;

        for(IntegerNode child : root){  /* Compiler error, says that the
            iterator returns Iterator<Node> and not Iterator<IntegerNode>*/
            total+=child.value;
        }

        System.out.println(total);
    }

}

有没有一种简单的方法可以解决这个问题,而无需将 Node 类中的 iterator() 方法复制到 IntegerNode 类中?

【问题讨论】:

    标签: java casting iterator extends


    【解决方案1】:

    我认为以下方法可行(未经测试,因此不能 100% 确定):

    class Node<T extends Node<T>> {
        public Iterator<T> iterator(){
            // basic tree traversal iterator
        }  
    }
    
    class IntegerNode extends Node<IntegerNode> {
        public static void main(String[]args) {
            IntegerNode root = new IntegerNode();
            int total = 0;
            for(IntegerNode child : root){  
                total += child.value;
            }
    
            System.out.println(total);
        }
    }
    

    这基本上是准标准inheritable builder pattern的扩展。

    【讨论】:

    • 谢谢!我想过使用泛型类型,但我忘记了你可以在扩展时设置类型。例如:IntegerNode>>>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多