我在下面的這個程序中遇到了一件事,它是......當在方法 numTest 中它用逗號分隔時,值“17”如何到達方法 isPrime 并且我找不到這個值“17”的任何轉移到這個方法?非常感謝你幫助我走得更遠。任何人都可以向我解釋價值“17”的運動嗎?// Demonstrate a method reference for a static method. // A functional interface for numeric predicates that operate // on integer values. interface IntPredicate { boolean test(int n); } // This class defines three static methods that check an integer // against some condition. class MyIntPredicates { // A static method that returns true if a number is prime. static boolean isPrime(int n) { if(n < 2) return false; for(int i=2; i <= n/i; i++) { if((n % i) == 0) return false; } return true; } // A static method that returns true if a number is even. static boolean isEven(int n) { return (n % 2) == 0; } // A static method that returns true if a number is positive. static boolean isPositive(int n) { return n > 0; } } class MethodRefDemo { // This method has a functional interface as the type of its // first parameter. Thus, it can be passed a reference to any // instance of that interface, including one created by a // method reference. static boolean numTest(IntPredicate p, int v) { return p.test(v); } public static void main(String args[]) { boolean result; // Here, a method reference to isPrime is passed to numTest(). result = numTest(MyIntPredicates::isPrime, 17); if(result) System.out.println("17 is prime."); // Next, a method reference to isEven is used. result = numTest(MyIntPredicates::isEven, 12); if(result) System.out.println("12 is even."); // Now, a method reference to isPositive is passed. result = numTest(MyIntPredicates::isPositive, 11); if(result) System.out.println("11 is positive."); } }
1 回答

月關寶盒
TA貢獻1772條經驗 獲得超5個贊
numTest
接受 anIntPredicate
和 an int
。AnIntPredicate
是一個函數式接口,具有一個接受 anint
并返回 a 的方法boolean
。
MyIntPredicates::isPrime
是與IntPredicate
接口匹配的方法引用,因此可以傳遞給numTest
.
numTest(MyIntPredicates::isPrime, 17)
調用isPrime(17)
通過調用p.test(v)
。
添加回答
舉報
0/150
提交
取消