我可以添加到类型B的类型A值的泛型集合,它扩展A,没有任何特殊的语法? [英] Can I add to a generic collection of type A values of type B ,which extends A, without any special syntax?

查看:144
本文介绍了我可以添加到类型B的类型A值的泛型集合,它扩展A,没有任何特殊的语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Stack<E> {
    public Stack () {....}
    public void push (E e) {....}
    public E pop () {....}
    public boolean isEmpty(){....}
}

public void pushAll (Collection<E> src) {
    for (E e: src){
        push(e)
    }
}

如果我写的话会有什么问题

I don't understand what will the problem if I'll write

Stack<number> numberStack = new Stack<Number>();
Collection<Integer> integers=...
numberStack.pushAll(integers);

Integer扩展Number,所以我可以添加一个Integers集合到 numberStack
但是我被告知这是一个错误编译 - 为什么?

Integer extends Number, so I can add a collection of Integers to numberStack. But I was told that this is an error compilation- Why?

推荐答案

只有接受具有相同类型参数集合 Stack

您应该这样写 pushAll 方法:

public void pushAll (Collection<? extends E> src)

这意味着您希望扩展 E 的一些类型的集合即你不关心它是什么具体类型,但它必须 E 或它的一些子类型)。

This means that you expect a Collection of some type that extends E (i.e. you don't care what specific type it is, but it must be E or some sub-type of it).

查看 Collection.addAll() :它的定义方式相同。

Look at the definition of Collection.addAll(): it's defined in the same way.

这篇关于我可以添加到类型B的类型A值的泛型集合,它扩展A,没有任何特殊的语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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