2 回答

TA貢獻(xiàn)1874條經(jīng)驗 獲得超12個贊
在java中,接口的方法總是公開的。所以你的界面可以變成
@FuctionalInterface
public interface NodeOperation {
boolean forAll(Tree node);
}
所以你寫了這行代碼
NodeOperation overTwenty = (node) -> node.getValue() < 20;
Wich 會為您創(chuàng)建一個接口實例,用于檢查節(jié)點的值是否低于 20
因此,假設(shè)您有一個值為 30 的 Tree 節(jié)點實例,如果您調(diào)用
overTwenty.forAll(node) //will return false
這個函數(shù)不是遞歸的。如果要將函數(shù)應(yīng)用于節(jié)點的所有子節(jié)點,則必須在 Tree 類上編寫遞歸方法
public class Tree{
...
public boolean recursiveNodeOperation(NodeOperation operation) {
if(!operation.forAll(this)) return false;
for(Tree child : children)
if(! child.recursiveNodeOperation(operation))
return false
return true ;
}
}
root.recursiveNodeOperation(overTwenty); //will return true if all the nodes of the Tree starting from root are lower than 20
此方法將遞歸應(yīng)用 Node 操作,因此將檢查 Tree 中的所有元素是否與您的函數(shù)匹配

TA貢獻(xiàn)1869條經(jīng)驗 獲得超4個贊
您創(chuàng)建的overTwenty
對象是一個函數(shù)。如果要在樹的節(jié)點中使用它,則必須在樹的節(jié)點上調(diào)用它的唯一方法。例如,您可以這樣稱呼它:
boolean result = overTwenty.forAll(root);
順便說一句,您的NodeOperation
interface 與 a 非常等價,Function<Tree, Boolean>
只是它返回的是原語boolean
而不是 class Boolean
。
添加回答
舉報