I am going through Generics Tutorial and was going through example to copy objects from array to collection.
Code
static void fromArrayToCollection(Object[] a, Collection<?> c) {
for (Object o : a) {
c.add(o); // Compile time error
}
}
I am thinking that I can pass object as parameter to collection and it should work without any issues but tutorial says
By now, you will have learned to avoid the beginner’s mistake of trying to use Collection as the type of the collection parameter.
Why does it say that passing Object as parameter type to Collection is not correct approach?
Updated:
static void fromArrayToCollection(Object[] a, Collection<Object> c) {
for (Object o : a) {
c.add(o); // Compile time error
}
}
The “beginner mistake” they’re referring to is saying
Collection<Object>when what you were trying to say is “any Collection/Collection of Anything.” It would in the abstract be perfectly legal to declare the method asCollection<Object>it just doesn’t meet the design goal of a method that takes in anything.We want to be able to do this:
That wouldn’t work if you made it
Collection<Object>.You can’t declare the parameter type as
Collection<Object>and have it work for multiple types like above because generic types aren’t covariant. It would be illegal to say, pass inList<String>to a method with an argument type ofCollection<Object>. ACollection<String>is not aCollection<Object>.Consider the standard example:
That’s why it’s illegal to declare it as
Collection<Object>and take a collection of anything.