How to override generic list return types in Java

I tried to override a method whose return type is a list in a subclass, as shown in the following example. Due to genericity problems, I cannot perform this operation in a subclass I can't change my superclass code, so how can I solve this problem? Anyone can guide me... Thank you very much in advance

Unable to update super course:

public class Animal {
           private String legs;
    }

public class TestSuper {

    public List<Animal> addAnimals() {
        return animals;
    }
}

Subclass:

public class Dog extends Animal {
         private String sound;
    }

public class TestSub extends TestSuper {

    public List<Dog> addAnimals() { --> I need to override this method but want return type as List of dogs
        return null;
    }
}

Solution

If the super class really can't be updated, I'm afraid you can't

If you can update superclasses:

In testsuper, you will use the public list addanimals() instead of public list < animal > addanimals()

What other solutions do you have:

You can use this practical method:

@SuppressWarnings("unchecked")
public static <T extends Animal> List<T> cast(List<Animal> animals,Class<T> subclass) {
    List<T> out = new ArrayList<T>();
    for (Animal animal : animals) {
        if (!subclass.isAssignableFrom(animal.getClass())) {
            // the "animal" entry isn't an instance of "subclass"
            // manage this case however you want ;)
        } else {
            out.add((T) animal);
        }
    }
    return out;
}

Then, call:

List<Dog> dogs = TheClassNameYouChose.cast(animals,Dog.class);
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
分享
二维码
< <上一篇
下一篇>>