关于双参数方法参考的困惑
Confusion about two-argument method reference
我对这个方法参考语法有点困惑。
counter()
期望 BiFunction
然而 HighTemp::lessThanTemp
是一个有效的参数,尽管 HighTemp.lessThanTemp()
只接受一个参数。
行中到底发生了什么:if (f.func(vals[i], v))
?
MCVE:
import java.util.function.BiFunction;
class Demo {
static class HighTemp {
private int hTemp;
HighTemp(int ht) { hTemp = ht; }
boolean lessThanTemp(HighTemp ht2) {
return hTemp < ht2.hTemp;
}
}
static <T> int counter(T[] vals, BiFunction<T,T,Boolean> f, T v) {
int count = 0;
for (int i=0; i < vals.length; i++) {
if (f.apply(vals[i], v)) { // THIS LINE
count++;
}
}
return count;
}
public static void main(String args[]) {
HighTemp[] weekDayHighs2 = { new HighTemp(32), new HighTemp(12),
new HighTemp(24), new HighTemp(19),
new HighTemp(18), new HighTemp(12),
new HighTemp(-1), new HighTemp(13) };
int count = counter(weekDayHighs2, HighTemp::lessThanTemp, new HighTemp(19));
System.out.println(count + " days had a high of less than 19");
}
}
看看 relevant documentation,其中注释:
The equivalent lambda expression for the method reference String::compareToIgnoreCase
would have the formal parameter list (String a, String b)
, where a
and b
are arbitrary names used to better describe this example. The method reference would invoke the method a.compareToIgnoreCase(b)
.
换句话说,HighTemp::lessThanTemp
等价于lambda表达式:
(a, b) -> a.lessThanTemp(b)
我对这个方法参考语法有点困惑。
counter()
期望 BiFunction
然而 HighTemp::lessThanTemp
是一个有效的参数,尽管 HighTemp.lessThanTemp()
只接受一个参数。
行中到底发生了什么:if (f.func(vals[i], v))
?
MCVE:
import java.util.function.BiFunction;
class Demo {
static class HighTemp {
private int hTemp;
HighTemp(int ht) { hTemp = ht; }
boolean lessThanTemp(HighTemp ht2) {
return hTemp < ht2.hTemp;
}
}
static <T> int counter(T[] vals, BiFunction<T,T,Boolean> f, T v) {
int count = 0;
for (int i=0; i < vals.length; i++) {
if (f.apply(vals[i], v)) { // THIS LINE
count++;
}
}
return count;
}
public static void main(String args[]) {
HighTemp[] weekDayHighs2 = { new HighTemp(32), new HighTemp(12),
new HighTemp(24), new HighTemp(19),
new HighTemp(18), new HighTemp(12),
new HighTemp(-1), new HighTemp(13) };
int count = counter(weekDayHighs2, HighTemp::lessThanTemp, new HighTemp(19));
System.out.println(count + " days had a high of less than 19");
}
}
看看 relevant documentation,其中注释:
The equivalent lambda expression for the method reference
String::compareToIgnoreCase
would have the formal parameter list(String a, String b)
, wherea
andb
are arbitrary names used to better describe this example. The method reference would invoke the methoda.compareToIgnoreCase(b)
.
换句话说,HighTemp::lessThanTemp
等价于lambda表达式:
(a, b) -> a.lessThanTemp(b)