我可以在本教程中穿越以下代码,我不明白
public int compareTo(Fruit compareFruit) {
//I don't understand this typecasting
int compareQuantity = ((Fruit) compareFruit).getQuantity();
//ascending order
return this.quantity - compareQuantity;
//descending order
//return compareQuantity - this.quantity;
}
为什么我们要
compareFruit
类型转换为Fruit
类型,而它已经是一个Fruit
类型?这似乎是多余的。getQuantity
法从何而来?我在哪里可以看到它的源代码?
我试图浏览一些文档,但找不到任何东西。
该强制转换实际上是多余的,因为 mathod compareTo 已经将水果作为参数,因此不需要它。
至于第二个问题,getQuantity 方法来自 Fruit 类本身:
public class Fruit implements Comparable<Fruit>{
// ...
public int getQuantity() {
return quantity;
}
// ...
}
1)为什么我们要类型转换将水果与水果类型进行比较,而它已经是水果类型了?这似乎是多余的
是的,这是多余的。无需进行类型转换。该行可以(必须)更改为:
int compareQuantity = compareFruit.getQuantity();
2)getQuantity方法从何而来?我在哪里可以看到它的源代码?
它在上面的Fruit
类中定义:
public class Fruit implements Comparable<Fruit> {
//...
public int getQuantity() {
return quantity;
}
//...
}
类型转换是多余的,你是对的。 getQuantity()
来自 Fruit 类的实现。看:
public int getQuantity() {
return quantity
}
- 在这种情况下,不需要铸造。语法是正确的 bu 强制转换是多余的。
- 它在 compareTo 方法上方几行的 Fruit 类中定义。
- 你是对的,这是多余的
-
getQuantity
是一种在Fruit
中声明的方法,或者在Fruit
扩展的类中声明。 它返回一个整数。