Generic array cast exception

Viewed 420

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.

3 Answers
Related