繁体   English   中英

运行时java.lang.ClassCastException

[英]java.lang.ClassCastException at runtime

我在以下代码中收到ClassCastException:

Destination[] destinations;
ArrayList<Destination> destinationsList = new ArrayList<Destination>(); 

// .....

destinations = (Destination[]) destinationsList.toArray();

我的Destination类如下所示:

public class Destination {

    private String code;

    Destination (String code) {

        this.code = code;

    }

   public String getCode () {

        return code;

   }
}

从语法上讲,我没有收到任何错误,这仅在运行时发生。 但这是令人困惑的,因为不是所有类都本质上是Object类的派生类吗? 如果是这样,为什么还会发生此强制转换错误?

toArray()返回一个Object[] 由于类型擦除,您需要的是toArray(T[] a) ,泛型集合无法创建类型化数组。

通过使用重载方法,可以帮助其创建Destination对象的类型化数组。

采用

destinations = destinationsList.toArray(new Destination[destinationList.size()]);

因为toArray返回的对象数组不是您的Destination[]

用它代替

destinations[] = destinationsList.toArray(new Destination[destinationList.size()]);

这将填充新的Destination Array对象并返回填充的数组。

编辑:

在@ZouZou的答案中以评论方式回答您的问题。

您需要new Destination[]因为Destination[]可以由Object[]引用,但反之亦然。

为了澄清事情,

String s = "hello";
Object o = s;
s = (String) o; //works

//but

String s = "hello";
Object o = s;
o = new Object;
s = (String) o; //gives you a ClassCastException because an Object
                //cannot be referred by a string

因为String具有通过继承在Object类中定义的所有属性,但是Object不具有String对象的属性。 这就是为什么放弃继承树是合法的,而向下转换则不合法。

由于泛型在语言中的放置方式,因此未在语言级别上实现。 也不要尝试这样的事情:

// Destination[] destinations;
    ArrayList<Destination> destinationsList = new ArrayList<Destination>();
    //add some destinations
    destinationsList.add(new Destination("1"));
    destinationsList.add(new Destination("2"));
    // .....
    Object[] destinations = destinationsList.toArray();
    destinations[1] = "2"; //simulate switching of one object in the converted array with object that is of other type then Destination
    for (Object object : destinations) {
        //we want to do something with Destionations
        Destination destination = (Destination) object;
        System.out.println(destination.getCode()); //exception thrown when second memeber of the array is processed
    }

用这个 :

destinations = destinationsList.toArray(new Destination[0]); //yes use 0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM