Answer the question
In order to leave comments, you need to log in
Why does the functional method take 2 parameters and the implementation takes one, but 2 arguments are specified in the usage?
There is this example code:
interface MyFunc<T> {
boolean func(T a, T b);
}
class HighTemp {
private int hTemp;
public HighTemp(int hTemp) {
this.hTemp = hTemp;
}
boolean sameTemp(HighTemp hTemp2) {
return hTemp == hTemp2.hTemp;
}
boolean lessThanTemp(HighTemp hTemp2) {
return hTemp < hTemp2.hTemp;
}
}
class App {
static <T> int counter(T[] vals, MyFunc<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),
new HighTemp(89),
new HighTemp(91),
new HighTemp(84),
new HighTemp(83)
};
count = counter(weekDayHighs, HighTemp::sameTemp, new HighTemp(89));
System.out.println("Дней, когда максимальная температура была 89: " + count);
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)
};
count = counter(weekDayHighs2, HighTemp::sameTemp, new HighTemp(12));
System.out.println("Дней, когда максимальная температура была 12: " + count);
count = counter(weekDayHighs, HighTemp::lessThanTemp, new HighTemp(89));
System.out.println("Дней, когда максимальная температура была меньше 89: " + count);
count = counter(weekDayHighs2, HighTemp::lessThanTemp, new HighTemp(19));
System.out.println("Дней, когда максимальная температура была меньше 19: " + count);
}
}
Answer the question
In order to leave comments, you need to log in
MyFunc<HighTemp> func = HighTemp::sameTemp;
the same as
MyFunc<HighTemp> func = new MyFunc<HighTemp>() {
@Override
boolean func(HighTemp a, HighTemp b) {
a.sameTemp(b);
}
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question