gpt4 book ai didi

Java函数式接口(interface)自动将第一个参数分配为类?

转载 作者:行者123 更新时间:2023-12-02 02:57:09 25 4
gpt4 key购买 nike

函数式接口(interface)定义了方法MyFunc,它有2个参数,但是当这个方法在HighTemp类中实现时,由于某种原因它只有1个参数,并且被调用使用f.func(vals[i], v),这个函数如何调用这个方法boolean sameTemp(HighTemp ht2),我缺少什么?

interface MyFunc<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 InstanceMethObjectRefDemo {
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(count + " days had a high of 89");

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(count + " days had a high of 12");

count = Counter(weekDayHighs, HighTemp::lessThanTemp, new HighTemp(89));
System.out.println(count + " days had a high less than 89");

count = Counter(weekDayHighs2, HighTemp::lessThanTemp, new HighTemp(19));
System.out.println(count + " days had a high of less then 19");
}
}

最佳答案

HighTemp::sameTemp 相当于:

(HighTemp t1, HighTemp t2) -> t1.sameTemp(t2);

关于Java函数式接口(interface)自动将第一个参数分配为类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42891992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com