A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://github.com/pmd/pmd/issues/2748 below:

[java] UnnecessaryCast false positive with unchecked cast · Issue #2748 · pmd/pmd · GitHub

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


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4