为什么 DefaultListModel.toArray() 会抛出

我正在尝试将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++;

}


互换的青春
浏览 167回答 3
3回答

HUH函数

toArray, 没有参数, 将返回一个Object[], 不能转换为 a cGenIndicator[]。相反,您可以使用重载方法获取要填充的数组作为参数:testArray = indObjList.toArray(new cGenIndicator[indObjList.size()]);编辑:DefaultListModel没有这个重载方法,Mia Kulpa。将 an 转换Object[]为 a 的一种方法cGenIndicator是使用流:testArray = Arrays.stream(indObjList.toArray())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(cGenIndicator.class::cast)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .toArray(cGenIndicator[]::new)

料青山看我应如是

DefaultListModel.toArray返回Object[],并且Object[]不能cGenIndicator[]直接转换为。您可以通过以下方式实现:Object[] objectArray = defaultListModel.toArray();int length = objectArray.length;cGenIndicator[] testArray = new cGenIndicator[length];System.arraycopy(objects, 0, testArray, 0, length);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java