簡體   English   中英

Java擴展參數化類

[英]Java extending parameterized class

我在試圖弄清楚以下問題時遇到了麻煩。 想象一下,我有一個泛型類Node<T>用於表示二叉樹的節點,其中包含一些方法。

    public class Node<T> {
       T info;
       Node<T> left;
       Node<T> right;

       public Node(T info) {this.info=info;}
       //and some methods
    }

現在我想為類型為Integer Node添加一個方法,它將對當前節點可以到達的所有節點求和:

    public int sum(){
        int sum = this.info;
        if(this.left!=null) sum+=left.sum();
        if(this.right!=null) sum+=right.sum();
        return sum;
    }
  

我不太確定如何做到這一點。 我想創建一個擴展Node<Integer>並在那里添加方法sum

    public class NodeOfIntegers extends Node<Integer>{
           
         public NodeOfIntegers (T info) {super();}

         public int sum(){...}
            
    }

但由於leftrightNode<Integer>類型而不是NodeOfIntegers我不能做left.sum()right.sum()

有沒有辦法在不重新定義leftright情況下做到這一點?

非常感謝。

使用像Stream提供的reduce函數:

public static class Node<T>{

        public Node(T value, Node<T> a, Node<T> b){
            this.value = value;
            this.a = a;
            this.b = b;
        }

        private final Node<T> a,b;
        private final T value;

        private T reduce(T start,BinaryOperator<T> operator){
            T reduced = operator.apply(start,value);
            if(a != null)reduced = a.reduce(reduced,operator);
            if(b != null)reduced = b.reduce(reduced,operator);
            return reduced;
        }
    }


    public static void main(String[] args) {
        Node<Integer> integerNode = new Node<>(4,new Node<>(4,null,null),new Node<>(2,null,null));
        System.out.println(integerNode.reduce(0, Integer::sum));
    }

您應該將 T 定義為

class Node<T extends Number> {

}

那么你可以將 sum 的函數寫為

int sum() {
    int sum = this.info.intValue();
}

我將在 Node 類中定義一個,而不是使用NodeOfInteger

public T combine(BinaryOperator<T> combiner) {
    T res = this.info;
    if (this.left != null) res = combine(res, this.left.combine(combiner);
    if (this.right != null) res = combine(res, this.right.combine(combiner);
    return res;
}

可以用作node.combine(Integer::sum)node.combine(String::concat)

(請注意,如果需要,這可以在 Node 類之外定義)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM