为了账号安全,请及时绑定邮箱和手机立即绑定

方法参考Static-小程序示例给建议

方法参考Static-小程序示例给建议

catspeake 2021-08-13 16:46:34
我在下面的这个程序中遇到了一件事,它是......当在方法 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)


查看完整回答
反对 回复 2021-08-13
  • 1 回答
  • 0 关注
  • 159 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号