为了账号安全,请及时绑定邮箱和手机立即绑定

为什么 DefaultListModel.toArray() 会抛出

为什么 DefaultListModel.toArray() 会抛出

互换的青春 2021-10-20 16:30:11
我正在尝试将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++;}
查看完整描述

3 回答

?
HUH函数

TA贡献1836条经验 获得超4个赞

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


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

编辑:


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


testArray = Arrays.stream(indObjList.toArray())

                  .map(cGenIndicator.class::cast)

                  .toArray(cGenIndicator[]::new)


查看完整回答
反对 回复 2021-10-20
?
料青山看我应如是

TA贡献1772条经验 获得超8个赞

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);


查看完整回答
反对 回复 2021-10-20
  • 3 回答
  • 0 关注
  • 166 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信