2 回答

TA貢獻1874條經驗 獲得超12個贊
在java中,接口的方法總是公開的。所以你的界面可以變成
@FuctionalInterface
public interface NodeOperation {
boolean forAll(Tree node);
}
所以你寫了這行代碼
NodeOperation overTwenty = (node) -> node.getValue() < 20;
Wich 會為您創建一個接口實例,用于檢查節點的值是否低于 20
因此,假設您有一個值為 30 的 Tree 節點實例,如果您調用
overTwenty.forAll(node) //will return false
這個函數不是遞歸的。如果要將函數應用于節點的所有子節點,則必須在 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
此方法將遞歸應用 Node 操作,因此將檢查 Tree 中的所有元素是否與您的函數匹配

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