Skip to content

[java] UnnecessaryCast false positive with unchecked cast #2748

@maikelsteneker

Description

@maikelsteneker

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positivePMD flags a piece of code that is not problematic

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions