Why does DefaultListModel.toArray() throw a ClassCastException?

Ted pottel :

I am trying to copy a DefaultListModel contents into an array. The following line causes the exception

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++;
}
xingbin :

DefaultListModel.toArray returns Object[], and Object[] can not be casted to cGenIndicator[] directly.

You can achieve it this way:

Object[] objectArray = defaultListModel.toArray();
int length = objectArray.length;

cGenIndicator[] testArray = new cGenIndicator[length];
System.arraycopy(objects, 0, testArray, 0, length);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=111577&siteId=1