在Java中如何将方法引用与泛型一起使用?
方法引用在Java8中引入,类似于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 包含" + count + " 4s");
count = myOp(MyArrayOps :: countMatching, strs, "Two");
System.out.println("strs 包含" + count + " Twos");
}
}输出结果
vals 包含3 4s strs 包含2 Twos
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便