java - 将整数对象转换为双掷错误
问题描述
我正在尝试编写一个实现 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);
}
}
但程序抛出错误说明:
java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Double
.
我不是想投加倍,而是加倍。为什么会抛出错误?
谢谢
解决方案
我不是想投加倍,而是加倍。为什么会抛出错误?
T
您的问题的根源是is Object
not的静态类型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;
}
这是静态类型安全的(以您可能在其他地方进行的任何不安全转换为模)。
请注意,如果T
替换为Integer
,编译器将使用不同的路径进行转换:
- 拆箱
Integer
到int
. - 将 扩大
int
到double
.
根据您编写 πr 2 h 表达式的确切方式,类型转换可能是不必要的。
推荐阅读
- javascript - 如何使键盘按钮不会在 javascript 中发送垃圾邮件。(造成延迟)
- node.js - 如何基于创建字段后触发的firebase云功能创建Stripe客户
- python - 为什么我的点子不起作用
- javascript - 使用javascript在html中具有值的AUTO SUM textboxt
- apache-spark-sql - Spark HDFS 直接读取与 Hive 外部表读取
- javascript - 加载本地 json 文件以对 js web 请求进行单元测试是一个好习惯吗?
- octave - 八度错误:返回列表中未定义的元素
- pandas - 如何将数据框中的多个条目合并为一个条目,Python
- ios - iphone x中的UICollection标头已满
- flutter - Flutter中,如何解决`AnimatedCrossFade`低效设计?