Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic array cast exception

I've got this Generic class, with a method returning a Generic Array:

public class ZTagField<T> extends JTextPane {
    public ZTagField(StringBasedFactory<T> factory) {
        assert (factory != null);
        this.factory = factory;
        init();
    }

    public T[] getItems() {
        ...
        T[] arrItems = (T[]) currentItems.toArray((T[])new Object[0]);
        return arrItems;
    }

And another one using it:

public class Xxx {
    ZTagField<clTag> txtTags = null;
    public Xxx() {
        txtTags = new ZTagField<clTag>(createFactory());
    }

    public clTag[] getSelectedTags() {
        return txtTags.getItems(); 
    }
}

This latter txtTags.getItems()gives me an exception : ==> Exception [Object cannot be cast to [clTag ????

Can anyone explain me why ?

I've trie to apply as much of this How to create a generic array, to no avail. I've got an ugly workaround :

return Arrays.asList(txtTags.getItems()).toArray(new clTag[0])

But I'd like to have it in then ZTagFieldClass.

like image 252
lvr123 Avatar asked Feb 03 '26 15:02

lvr123


1 Answers

Works as designed: at runtime there is no generic type.

It gets erased, and an array of Object is created. An array of Object can not be cast to another kind of array.

This is one of the restrictions of Java generics, based on the way how they are implemented.

That is way you are advised to be careful using arrays together with generics. You might prefer to use a generic List instead.

And just to be clear about this: yes, you can get arrays to work with generics, as elegantly shown by the other answers. But: you spend your time fighting symptoms doing so. Arrays and generics don't go together nicely in Java. Accept that, use generic lists and thus: fix the problem instead of working around it.

like image 83
GhostCat Avatar answered Feb 05 '26 03:02

GhostCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!