[英]Understanding lambdas and/or predicates
我是Java 8的新手,我正試圖解決為什么最后一次測試是錯誤的。
@Test
public void predicateTest() {
Predicate<Boolean> test1 = p -> 1 == 1;
Predicate<Boolean> test2 = p -> p == (1==1);
System.out.println("test1 - true: "+test1.test(true));
System.out.println("test1 - false: "+test1.test(false));
System.out.println("test2 - true: "+test2.test(true));
System.out.println("test2 - false: "+test2.test(false));
}
輸出 :
test1 - true: true
test1 - false: true
test2 - true: true
test2 - false: false
你的第一個Predicate
即
Predicate<Boolean> test1 = p -> 1 == 1;
可以表示為
Predicate<Boolean> test1 = new Predicate<Boolean>() {
@Override
public boolean test(Boolean p) {
return true; // since 1==1 would ways be 'true'
}
};
因此無論您傳遞給上述test
方法的價值如何,它始終只返回true 。
另一方面,第二個Predicate
即
Predicate<Boolean> test2 = p -> p == (1==1);
可以表示為
Predicate<Boolean> test2 = new Predicate<Boolean>() {
@Override
public boolean test(Boolean p) {
return p; // since 'p == true' would effectively be 'p'
}
};
因此,無論您將傳遞給上述test
方法的boolean
值,它都將按原樣返回 。
然后,您可以關聯如何調用與匿名類的每個實例test1
和test2
相對應的方法test
以及可能的輸出。
這是假的,因為p
是false
, 1==1
是true
所以:
false == true
計算結果為false。
換句話說,當您使用false
作為參數調用此函數時:
Predicate<Boolean> test2 = p -> p == (1==1);
它可以看作:
Predicate<Boolean> test2 = p -> false == (1==1);
順便說一句,上面的謂詞將返回你傳遞的任何輸入,所以基本上它是:
Predicate<Boolean> test2 = p -> p;
謂詞test1 =值 - > 1 == 1;
謂詞test2 =值 - >值==(1 == 1);
測試用例 :System.out.println(“test2 - false:”+ test2.test(false));
輸出 :false
說明 :
您正在使用“false”調用test2方法,因此您的方法的執行將如下所示:
false == (1==1) => false == true => false
所以最終的答案是錯誤的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.