开发者

How to add element to a generic collection

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?


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

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


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

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

It won't require any casting either.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜