如何結合 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 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告