java 如何将元素添加到泛型集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5386272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:52:52  来源:igfitidea点击:

How to add element to a generic collection

java

提问by user496949

I am wondering how to add a specialized object to a generic collection

我想知道如何将专门的对象添加到通用集合中

I am using the following code

我正在使用以下代码

Collection<T> c;
Class1 object1 = new Class1()
c.add((T)object1)

Is this the correct way?

这是正确的方法吗?

回答by Greg

If your collection is intended to hold only instances of Class1, you should do:

如果您的集合仅用于保存 Class1 的实例,您应该执行以下操作:

Collection<Class1> c;
Class1 object1 = new Class1();
c.add(object1);

回答by anubhava

Or you have the option of keeping your collection really open using wildcardgenerics (though I didn't understand your intent behind this requirement) using code like this:

或者您可以选择使用wildcard泛型(虽然我不明白您在此要求背后的意图)使用如下代码保持您的集合真正开放:

Collection<?> c;
Class1 object1 = new Class1()
c.add(object1)

It won't require any casting either.

它也不需要任何铸造。