开发者

How to add element to a generic collection

开发者 https://www.devze.com 2023-02-18 17:22 出处:网络
I am wondering how to add a specialized object to a generic collection开发者_高级运维 I am using the following code

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

精彩评论

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