首页 > 解决方案 > Array type erasure

问题描述

Why the following code is potentially not type-safe (the compiler generates a warning)?

class ArrayTypeErasure<T> {
    private T[] elements;

    public void setElements(List<T> elements) {
        this.elements = (T[]) elements.toArray();
    }
}

I'm trying to think of any situations when the code would fail, but so far it's only me who is failing.

标签: javagenerics

解决方案


Simply because List#toArray() returns an Object[] so there is no guarantee from this method that it would return T[]

Now, in practice, it's ok since you always know that it will return the wanted type

You could use @SuppressWarnings("unchecked") to avoid this warning from appearing


推荐阅读