Here are several questions related to type mismatch using generics in Java, but I was not able to find anything corresponding to my case.

I wonder why this error happens in below code?

Type mismatch: cannot convert from element type Object to String

in line

for (String element : arg.someMethod())

But if

SomeInterface arg

is changed to

SomeInterface<?> arg

it works. Why list parameter type is erased if it is not connected to interface type parameter?

import java.util.List;

public class TypeMismatchExample
{
    interface SomeInterface<P extends Object>
    {
        P someParametrizedMethod();

        List<String> someMethod();
    }

    void example(SomeInterface arg)
    {
        for (String element : arg.someMethod())
        {
            // do something
        }
    }
}
有帮助吗?

解决方案

When you have a raw type in your code, all generic type information in that class is lost -- thus, the compiler does not know that someMethod returns a List of type String.

The relevant portion of the JLS: Raw Types

The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) M of a raw type C that is not inherited from its superclasses or superinterfaces is the raw type that corresponds to the erasure of its type in the generic declaration corresponding to C.

So since you declared the method parameter as SomeInterface, which is a raw type, you cannot take advantage of the generic someMethod, even though its generic type parameter is not the same as P.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top