我在試圖弄清楚以下問題時遇到了麻煩。想象一下,我有一個Node<T>用于表示二叉樹節點的通用類,其中包含一些方法。
public class Node<T> {
T info;
Node<T> left;
Node<T> right;
public Node(T info) {this.info=info;}
//and some methods
}
現在我想Node為 type 的 s添加一個方法Integer,它將對當前節點可以到達的所有節點求和:
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(){...}
}
但是因為leftandright是型別Node<Integer>而不是NodeOfIntegers我不能做left.sum()and right.sum()。
有沒有辦法在不重新定義left和的情況下做到這一點right?
非常感謝。
uj5u.com熱心網友回復:
使用reduce類似Stream提供的函式:
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));
}
uj5u.com熱心網友回復:
您應該將 T 定義為
class Node<T extends Number> {
}
那么你可以將 sum 的函式寫為
int sum() {
int sum = this.info.intValue();
}
uj5u.com熱心網友回復:
NodeOfInteger我將在 Node 類中定義一個,而不是使用一個類
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 類之外定義)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/323519.html
