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.
精彩评论