2

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++;
}
Sotirios Delimanolis
  • 263,859
  • 56
  • 671
  • 702
Ted pottel
  • 6,721
  • 19
  • 72
  • 130

3 Answers3

7

toArray, without an argument, will return an Object[], that can't be cast to a cGenIndicator[]. Instead, you can use the overloaded method that gets an array to fill as an argument:

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

EDIT:

DefaultListModel does not have this overloaded method, Mia Kulpa. One way to convert an Object[] to a cGenIndicator is with streams:

testArray = Arrays.stream(indObjList.toArray())
                  .map(cGenIndicator.class::cast)
                  .toArray(cGenIndicator[]::new)
Mureinik
  • 277,661
  • 50
  • 283
  • 320
2

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);
Kamil Gosciminski
  • 15,392
  • 4
  • 45
  • 65
xingbin
  • 25,716
  • 8
  • 51
  • 94
1

The DefaultModel::toArray() method produces an Object[] not a cGenIndicator[].

If this was a List, you would use toArray(new cGenIndicator[0]) instead. For more information, refer to the javadoc or to https://stackoverflow.com/a/5374346/139985. Note that the latter talks about String[] but the principle is exactly the same.

For a DefaultModelList you do not have this option:

  • The simple solution is to get rid of the type cast, and change to type of testArray to Object[].

  • You could also explicitly copy the elements of the Object[] to a more appropriately typed array. Whether this is worthwhile will depend on how you are going to use the array.


And please fix your class / interface names to conform to the Java style rules. cGenIndicator should be CGenIndicator ... or something more readable.

Stephen C
  • 669,072
  • 92
  • 771
  • 1,162