Affects PMD Version: 6.26.0
Description:
The rule UnnecessaryCast tells me that I'm doing a cast that is not necessary, but omitting it results in a compiler error.
This refers to the cast of (T[])list.toArray() from the example below. The toArray() methods returns an Object[], not a T[]. There is an alternative method available that takes an array as argument and uses the type of that for its return value, but in a case like this, where T is a type parameter instead of a concrete type for which an array can be initialized, that alternative method can't be used either.
Code Sample demonstrating the issue:
/** Returns all elements from the given iterator in a new array */
@SuppressWarnings("unchecked")
public static <T> T[] asArray(Iterator<T> elements) {
final List<T> list = new ArrayList<T>();
while( elements.hasNext() ) list.add( elements.next() );
T[] result = toArrayC( (Class<T>)null, list );
if( result == null ) result = (T[])list.toArray(); // <----- this cast is really necessary
return result;
}
Running PMD through: CLI
Affects PMD Version: 6.26.0
Description:
The rule UnnecessaryCast tells me that I'm doing a cast that is not necessary, but omitting it results in a compiler error.
This refers to the cast of
(T[])list.toArray()from the example below. ThetoArray()methods returns anObject[], not aT[]. There is an alternative method available that takes an array as argument and uses the type of that for its return value, but in a case like this, whereTis a type parameter instead of a concrete type for which an array can be initialized, that alternative method can't be used either.Code Sample demonstrating the issue:
Running PMD through: CLI