【发布时间】:2018-01-17 15:52:48
【问题描述】:
我遇到了这个例子:
package br.com.teste;
class HighTemp {
private int hTemp;
HighTemp(int ht) {
hTemp = ht;
}
boolean sameTemp(HighTemp ht2) {
return hTemp == ht2.hTemp;
}
}
interface MyFunc152<T> {
boolean func(T v1, T v2);
}
class InstanceMethWithObjectRefDemo {
static <T> int counter(T[] vals, MyFunc152<T> f, T v) {
int count = 0;
for (int i = 0; i < vals.length; i++)
if (f.func(vals[i], v)) 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) };
count = counter(weekDayHighs, HighTemp::sameTemp, new HighTemp(89));
System.out.println(count + " days had a same of 89");
}
}
为什么会这样?特别是方法引用被传递给带有接口参数的函数的部分。
count = counter(weekDayHighs, HighTemp::sameTemp, new HighTemp(89));
为什么 HighTemp::sameTemp 与 MyFunc152 一样有效?如果 sameTemp 不是静态的,为什么传递 HighTemp::sameTemp 不会产生编译错误?
【问题讨论】: