为什么DefaultListModel.toArray()抛出ClassCastException?

Ted*_*tel 2 java arrays

我试图将DefaultListModel内容复制到数组中.以下行导致异常

testArray =(cGenIndicator [])indObjList.toArray();

void testCasting() {
    DefaultListModel<cGenIndicator> indObjList;
    indObjList = new DefaultListModel<cGenIndicator>();
    indObjList.addElement(new cGenIndicator(null, null));

    cGenIndicator[] testArray;
    try {
        // This line causses exception saying
        // [Ljava.lang.Object; cannot be cast to [LIndicator.cGenIndicator;
        testArray = (cGenIndicator[]) indObjList.toArray();
    } catch(Exception e) {
        test++;
    }

    test++;
}
Run Code Online (Sandbox Code Playgroud)

Mur*_*nik 7

toArray没有参数,将返回一个Object[],不能被强制转换为cGenIndicator[].相反,您可以使用重载方法获取数组作为参数填充:

testArray = indObjList.toArray(new cGenIndicator[indObjList.size()]);
Run Code Online (Sandbox Code Playgroud)

编辑:

DefaultListModel没有这种重载方法,Mia Kulpa.将一个转换Object[]为a的一种方法cGenIndicator是使用流:

testArray = Arrays.stream(indObjList.toArray())
                  .map(cGenIndicator.class::cast)
                  .toArray(cGenIndicator[]::new)
Run Code Online (Sandbox Code Playgroud)

  • 它是一个`DefaultListModel`,而不是`List`的实例 (2认同)