今天翻《Java 8 编程参考官方教程》的时候看到一段代码:
public class InstanceMethWithObjectRefDemo {
private static <T> int counter(T[] vals, MyFunc<T> f, T v2) {
int count = 0;
for (T v1 : vals) {
if (f.func(v1, v2)) count++;
}
return count;
}
public static void main(String[] args) {
int count;
HighTemp[] weekDayHighs = {
new HighTemp(89), new HighTemp(82),new HighTemp(90), new HighTemp(89),
new HighTemp(89), new HighTemp(91),new HighTemp(84), new HighTemp(83)
};
count = counter(weekDayHighs, HighTemp::sameTemp, new HighTemp(89));
System.out.println(count + " days had a high of 89");
count = counter(weekDayHighs, HighTemp::lessThanTemp, new HighTemp(89));
System.out.println(count + " days had a high less than of 89");
}
}
@FunctionalInterface
interface MyFunc<T> {
boolean func(T v1, T v2);
}
class HighTemp {
private int hTemp;
public HighTemp(int hTemp) {
this.hTemp = hTemp;
}
boolean sameTemp(HighTemp ht2) {
return this.hTemp == ht2.hTemp;
}
boolean lessThanTemp(HighTemp ht2) {
return this.hTemp < ht2.hTemp;
}
}
这里有一段:
count = counter(weekDayHighs, HighTemp::sameTemp, new HighTemp(89));
看到的时候有点疑问,HighTemp#sameTemp
怎么就和MyFunc
函数式接口兼容了呢?MyFunc
需要两个T
参数和一个boolean
返回值。而HighTemp#sameTemp
是一个参数一个返回值。愣了一会儿,想起隐式参数这回事,恍然大悟。
一般情况下方法都会有super
和this
,所以相当于sameTemp
方法的声明是:
boolean sameTemp(HighTemp this, HighTemp ht2);
这样就和MyFunc
兼容了。
接口中唯一抽象方法的命名并不重要,因为函数式接口就是对某一行为进行抽象,主要目的就是支持Lambda表达式。
总结
有些知识点看的时候理解,但不到实际应用,还真容易忘,但是看过的东西总比没有学习过要好,因为在你需要它的时候,你能想起来,帮助你解决问题。