我正在尝试编写一个实现Comparable接口的'Cup'类。
我的代码:
class Cup<T> implements Comparable<T>{
public T radius;
public T height;
public Cup(T radius, T height){
this.radius = radius;
this.height = height;
}
public double getVolume(){
return (double) radius * (double) radius* (double) height* 3.14 ; // throwing error
}
public int compareTo(Object cup){
if(getVolume()== ((Cup) cup).getVolume()){ // cannot access java.lang.Comparable
return 0;
}
else if(getVolume() > ((Cup) cup).getVolume()){
return 1;
}
else if(getVolume() < ((Cup) cup).getVolume()){
return -1;
}
return -2;
}
}
class test{
public static void main(String[] args) {
Cup<Integer> mycup = new Cup<Integer>(5,5);
Cup<Integer> momscup = new Cup<Integer>(7,7);
mycup.compareTo(momscup);
}
}
Run Code Online (Sandbox Code Playgroud)
但是程序抛出错误,指出:
java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Double。
我不是要加倍,而是要加倍。为什么会引发错误?
谢谢
我不是要加倍,而是要加倍。为什么会引发错误?
你的问题的根源是静态类型的T是Object不是Integer。因此,编译器已确定以下路径可能有效:
Double(需要运行时检查)Double到double。问题是Integer无法转换为Double。
最好的解决方案是这样的:
class Cup<T extends Number> implements Comparable<T> {
...
public double getVolume(){
return radius.doubleValue() * radius.doubleValue()
height.doubleValue() * Math.PI;
}
Run Code Online (Sandbox Code Playgroud)
这是静态类型安全的(对您可能在其他地方进行的任何不安全的转换进行模运算)。
请注意,如果T被替换为Integer,则编译器将使用其他路径进行转换:
Integer对的装箱int。int到double。 根据您确切地编写?r 2 h表达式的方式,类型转换可能是不必要的。