首页 > 解决方案 > 将整数对象转换为双掷错误

问题描述

我正在尝试编写一个实现 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.

我不是想投加倍,而是加倍。为什么会抛出错误?

谢谢

标签: java

解决方案


我不是想投加倍,而是加倍。为什么会抛出错误?

T您的问题的根源是is Objectnot的静态类型Integer。因此编译器确定以下路径可能有效:

  1. 将对象的实际类型转换为Double(需要运行时检查)
  2. 拆箱Doubledouble.

问题是Integer不能转换为Double.

最好的解决方案是这样的:

class Cup<T extends Number> implements Comparable<T> {
    ...
    public double getVolume(){
        return radius.doubleValue() * radius.doubleValue() 
               height.doubleValue() * Math.PI;
    }

这是静态类型安全的(以您可能在其他地方进行的任何不安全转换为模)。


请注意,如果T替换为Integer,编译器将使用不同的路径进行转换:

  1. 拆箱Integerint.
  2. 将 扩大intdouble.

根据您编写 πr 2 h 表达式的确切方式,类型转换可能是不必要的。


推荐阅读