java - 方法引用 Static - 小程序示例给建议

标签 java methods reference

关于一件事,我被下面的这个程序卡住了,它是......当方法 numTest 中它被逗号分隔时,值“17”如何到达方法 isPrime 并且我找不到这个值的任何传输“17"到这个方法?非常感谢您帮助我走得更远。谁能解释一下值(value)“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."); 
  } 
}

最佳答案

numTest 接受一个 IntPredicate 和一个 intIntPredicate 是一个函数式接口(interface),它有一个接受 int 并返回 boolean 的方法。

MyIntPredicates::isPrime 是与 IntPredicate 接口(interface)匹配的方法引用,因此可以传递给 numTest

numTest(MyIntPredicates::isPrime, 17) 通过调用 p.test(v) 调用 isPrime(17)

关于java - 方法引用 Static - 小程序示例给建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52033880/

相关文章:

java - 有效地找到可变数量的字符串集的交集

java - 将一个对象的 ArrayList 内容传输到另一个对象

methods - 如何获取类型化函数的方法字段(Go)

java - Java 中可以将一个方法传递给另一个方法吗

c# - 松散耦合、无引用的程序集——如何确保它在exe项目的\bin\Debug文件夹中进行调试?

java - 如何处理 selenium webdriver 中的弹出窗口(不警报)?

java - jpql和hibernate年龄差异

java - 如何使用 Commons compress 打包太大并导致内存不足崩溃的文件?

c - 在 C 中通过引用传递的 3d 数组

Java - 即时改变倒数计时器的速度