对于以下代码段,在calculateOnShipments中,一个参数接受以Shipment为输入的函数并返回Double的形式
Function<Shipment, Double> f
1)为什么可以通过Shipment :: calculateWeight调用它?尽管它返回双精度值,但是它不接受任何参数。
public double calculateWeight()
2)我尝试注释掉calculateWeight(),但保留calculateWeight(Shipment s1),然后出现错误msg
“无法从类型Shipment静态引用非静态方法calculateWeight(Shipment)”
此消息是什么意思?为什么说静态引用?在我对calculateWeight()进行注释之前,为什么没有此错误消息?
public 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;
}
}
对于以下代码段,在calculateOnShipments中,一个参数接受以Shipment作为输入的函数并返回Double Function
Shipment::calculateWeight
可以调用它?calculateWeight()
尽管它返回双精度,但不接受任何参数