gpt4 book ai didi

java - 为什么可以用无参方法来代替Function

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

对于以下代码片段,在 calculateOnShipments 中,一个参数接受以 Shipment 作为输入、以 Double 作为输出的函数。

Function<Shipment, Double> f

1) 为什么可以使用Shipment::calculateWeight调用? calculateWeight() 不接受任何参数,尽管它返回 Double

public double calculateWeight()

2) 我尝试注释掉 calculateWeight() 但保留 calculateWeight(Shipment s1),然后出现错误消息

"Cannot make a static reference to the non-static method calculateWeight(Shipment) from the type Shipment"

这条消息是什么意思?为什么说静态引用?在我评论 calculateWeight() 之前,为什么没有错误消息?

class Shipment {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Shipment> l = new ArrayList<Shipment>();
l.add(new Shipment());
l.add(new Shipment());
Shipment shipment1 = new Shipment();
// Using an anonymous class
List<Double> lw = shipment1.calculateOnShipments(l, Shipment::calculateWeight);
System.out.println(lw);//[0.0,0.0]
}

public double calculateWeight() {
double weight = 0;
// Calculate weight
return weight;
}

public double calculateWeight(Shipment s1) {
double weight = 1;
// Calculate weight
return weight;
}

public List<Double> calculateOnShipments(
List<Shipment> l, Function<Shipment, Double> f) {
List<Double> results = new ArrayList<>();
for (Shipment s : l) {
results.add(f.apply(s));
}
return results;
}
}

最佳答案

why it can be called by Shipment::calculateWeight? calculateWeight() does not accept any parameter, although it return double

可以使用方法引用来调用它,因为方法引用代表调用方法的代码 calculateWeightshipment上它被接受作为 Function<Shipment, Double> 的输入。阅读这些内容以获得进一步的相互关系——

shipment -> shipment.calculateWeight()

或更进一步

new Function<Shipment, Double>() {
@Override
public Double apply(Shipment shipment) {
return shipment.calculateWeight();
}
})
<小时/>

I try to comment out the calculateWeight() but keep the calculateWeight(Shipment s1), then there is a error msg

现在,如果您已经理解了上面的 lambda 表示,那么如果没有调用 calculateWeight ,则方法引用是不可能的。方法需要一个装运,其中一个是调用该方法的实例,另一个应该传递给方法以用作参数。这可能是这样的——

shipment -> shipment.calculateWeight(shipment1)
<小时/>

请注意,将方法转换为 static比如

public static double calculateWeight(Shipment s1)

将导致推断方法引用接受实例作为参数本身,并且工作方式如下:

List<Double> lw = shipment1.calculateOnShipments(l, Shipment::calculateWeight)

哪里Shipment::calculateWeight代表shipment -> calculateWeight(shipment) .

关于java - 为什么可以用无参方法来代替Function<T,R>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60568897/

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