In Lambda Ausdrücke studiere ich das folgende Beispiel. Aber ich verstehe die Logik des Codes hier nicht.Wie ist es möglich, hier eine Methode mit einem Argument auf ein Ziel mit zwei in Lambda zu verweisen?
Wie oder wo die Funktion sameTemp ausgeführt wird. Weil ich es als eine Methodenreferenz passiere, aber dann rufe ich f.func(vals[i], v)
an, obwohl sameTemp 1 Argument annimmt.
package lambda;
//A functional interface that takes two reference arguments
//and returns a boolean result.
interface MyFunc5<T> {
boolean func(T v1, T v2);
}
class HighTemp {
private int hTemp;
HighTemp(int ht) {
hTemp = ht;
}
boolean sameTemp(HighTemp ht2) {
return hTemp == ht2.hTemp;
}
boolean lessThanTemp(HighTemp ht2) {
return hTemp < ht2.hTemp;
}
}
public class InstanceMethWithObjectRefDemo {
static <T> int counter(T[] vals, MyFunc5<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;
// Create an array of HighTemp objects.
HighTemp[] weekDayHighs = { new HighTemp(89), new HighTemp(82), new HighTemp(89)};
//Why there is no error referencing sameTemp to the place of MyFunc5<T> f because MyFunc5<T> f
//has 2 args while sameTemp has 1
count = counter(weekDayHighs, HighTemp::sameTemp, new HighTemp(89));
System.out.println(count + " days had a high of 89");
}
}