Java generics and return types

I've just come across something I don't understand Why is every loop illegal when the second is the same?

public interface SomeInterface<T> {
   List<SomeNamedObject> getObjects();
   void doSomething(P1 p1,T p2);
}

public class SomeNamedObject {
    private String text;
}

public class Clazz {

    private SomeInterface someInterface;

    ...

    public void someMethod() {
       // Error Type mismatch: cannot convert from element type Object to TestClass.someNamedObject
       for (SomeNamedObject someNamedObject :  someInterface.getObjects()) {
             // This loop won't compile as the someInterface.getObjects returns just a List and not a List<SomeNamedObject>
       }

       // Warning Type safety: The expression of type List needs unchecked 
       // conversion to conform to List<TestClass.someNamedObject>
       List<SomeNamedObject> objects = someInterface.getObjects();
       for (SomeNamedObject someNamedObject :  objects) {
             // This loop compiles 
       }
    }
}

Solution

Because your instance variable private someinterface does not specify its generic type parameters, all using generics will be disabled for someinterface This means someinterface Getobjects() has the original return type list instead of list < somenamedobject & gt This is why the first example was not compiled In the second example, list < somenamedobject > objects = someinterface Getobjects() is adding explicit types to the list When you do this, you will see a warning because type safety cannot be guaranteed If getobjects () is defined as list getobjects () without type parameter, then this will be the same behavior you see

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>