如何结合 Java 中的泛型来使用方法引用?


方法引用**在Java 8中引入了与lambda**表达式类似的概念。它允许我们引用**方法**或**构造函数**而无需执行它们。方法引用和 lambda 表达式需要一个目标**类型**,该类型由兼容的函数**接口**组成。我们还可以在 java 中将方法引用与泛型**类**和泛型**方法**一起使用。

示例

interface MyFunc<T> {
   int func(T[] vals, T v);
}
class MyArrayOps {
   static<T> int countMatching(T[] vals, T v) {
      int count = 0;
      for(int i=0; i < vals.length; i++)
         if(vals[i] == v)
            count++;
      return count;
   }
}
public class GenericMethodRefTest {
   static<T> int myOp(MyFunc f, T[] vals, T v) {
      return f.func(v als, v);
   }
   public static void main(String args[]) {
      Integer[] vals = { 1, 2, 3, 4, 2, 3, 4, 4, 5 };
      String[] strs = { "One", "Two", "Three", "Two" };
      int count;
      count = myOp(MyArrayOps :: countMatching, vals, 4);
      System.out.println("vals contains " + count + " 4s");
      count = myOp(MyArrayOps :: countMatching, strs, "Two");
      System.out.println("strs contains " + count + " Twos");
   }
}

输出

vals contains 3 4s
strs contains 2 Twos

更新于: 11-7-2020

775 次浏览

开启你的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.