为什么不能将B的超类对象放入Container&lt ;?超级B&gt ;? [英] Why can't I put an object of superclass of B into Container<? super B>?

查看:60
本文介绍了为什么不能将B的超类对象放入Container&lt ;?超级B&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的代码.看来我无法将作为类Vehicle的超类的类Nonlife的对象放入类型为Collection<? super Vehicle> ALTHOUGH 的容器中,其中没有关键字"super".在通配符类型中,仅类VehicleSUV的对象是类Vehicle的子类是可行的.有人可以给我一些建议吗?

I have the code below. It seems that I can't put an object of class Nonlife that is a superclass of class Vehicle into a container of type Collection<? super Vehicle> ALTHOUGH there is a keyword "super" in the wildcard type, and only objects of class Vehicle and SUV that is a subclass of class Vehicle are feasible. Could someone give me some advice?

public class SUV extends Vehicle

public class Vehicle extends Nonlife implements Externalizable

public class Nonlife extends Thing

public class Thing implements Comparable<Thing>, Serializable

public class SupperWildcardTest20200830 {
    
    public static void main(String[] args) {
        Collection<Thing> coll = new ArrayList<>();
        appendVehicle2Collection(coll);
        appendSuv2Collection(coll);
        for (Thing el: coll) {
            System.out.println("" + el);
        }
    }
    
    public static void appendVehicle2Collection(Collection<? super Vehicle> coll) {
        coll.add(new Vehicle());
    }
    
    public static void appendSuv2Collection(Collection<? super Vehicle> coll) {
        coll.add(new SUV());
    }
    
    public static void appendNolife2Collection(Collection<? super Vehicle> coll) {
        /**
         * incompatible types: Nonlife cannot be converted to CAP#1
         *  where CAP#1 is a fresh type-variable:
         *    CAP#1 extends Object super: Vehicle from capture of ? super Vehicle
         */
        coll.add(new Nonlife());
    }
}

推荐答案

对于Collection<? super Vehicle>,您唯一可以肯定的是它是Vehicle的集合,或者是Vehicle的超类型的集合.因此,您唯一可以确定可以放入此集合的东西是Vehicles.因此,您可以将NonLifes的Collection传递给该方法,但仍然可以只将Vehicles或子类型放入该方法中的Collection.

The only thing you know for sure about Collection<? super Vehicle> is that it is a collection of Vehicles, or a collection of a supertype of Vehicles. So the only thing you know for sure that you can put into this collection are Vehicles. So you are allowed to pass a Collection of NonLifes to the method, but you may still only put Vehicles or subtypes into the collection within the method.

通常:使用super时,您可以将提到的类型或子类型的值放入其中.使用扩展,您可以从集合中检索提到的类型,也可以将它们作为超类型检索.

In general: with super, you can put values of the mentioned type in it, or subtypes. With extends you can retrieve the mentioned type from the collection, or retrieve them as a supertype.

这篇关于为什么不能将B的超类对象放入Container&lt ;?超级B&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆