For the following code snippet, in calculateOnShipments, one parameter accepts a function with Shipment as input and Double as output.
Function<Shipment, Double> f
1) Why can it be called using Shipment::calculateWeight? calculateWeight() does not accept any parameter, although it returns Double
public double calculateWeight()
2) I try to comment out the calculateWeight() but keep the calculateWeight(Shipment s1), then there is an error message
"Cannot make a static reference to the non-static method calculateWeight(Shipment) from the type Shipment"
What does this message mean? why it said a static reference? before I comment the calculateWeight(), why was there no error message?
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;
}
}