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
  • 274,122
  • 60
  • 696
  • 724
Ted pottel
  • 6,869
  • 21
  • 75
  • 134

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
  • 297,002
  • 52
  • 306
  • 350
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
  • 16,547
  • 8
  • 49
  • 72
xingbin
  • 27,410
  • 9
  • 53
  • 103
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
  • 698,415
  • 94
  • 811
  • 1,216