False positive ClassCastExceptionWithToArray with generics
A source code analyzer
Brought to you by:
adangel,
juansotuyo
pmd reports "This usage of the Collection.toArray() method will throw a ClassCastException." for the first code line of this "method":
public static <E> E[] toArrayWrapped(Collection<E> c) { E[] retVal = (E[]) c.toArray(); return retVal; }
But this is not true. It would probably be true if E were a concrete type, but for generic types with erasure Object it is not, and in fact such a cast seems to be the shortest way of getting an array of type E.
Diff:
Yes, you won't get a class cast exception on this line.
However, this utility method is still questionable for me.
Consider this test class:
As you see, you'll get your class cast exception later on, as your method "toArrayWrapped" won't always return the correct array type.
Btw. - it works, if you use
Arrays.asList("foo", "bar")
because the collection implementation internally uses then a String[] array. ArrayList however uses a Object[] array to store the data.The correct way to convert a collection to an array is still using
Collection.toArray(T[] a)
see javadoc.That's why I'm closing this bug as won't fix. Feel free to reopen it, if you see a different solution.