Java collection methods
I am starting to learn Java and I have a question about generics.
In this method from the interface Collection<E>
:
boolean containsAll( Collection <?> c);
boolean removeAll(Collection<?> c);
boolean retainAll ( Collection <?> c);
Why parameter Collection <?> c
instead of Collection <E> c
?
Thank you so much
source to share
The JDK developers wanted the code to look like this:
Collection<String> strings = Arrays.asList("foo", "bar", "baz");
Collection<Object> objects = Arrays.asList("foo", 123);
strings.removeAll(objects);
// strigns now contains only "bar" and "baz"
(The above code can't compile exactly because I can't remember how it Arrays.asList()
grabs the type parameters, but it should get a point.)
That is, since you can call .equals()
on any pair of objects and get meaningful results, you don't need to restrict those methods to a specific element type.
source to share
Because the type parameter E
must be specified and the wildcard ?
works for every type. The subtle difference is that
-
E
means any specified type -
?
means any unknown type
Since methods must operate on a collection of any unknown type, they do not specify a type parameter at all. E
is a type variable. ?
is not a variable, is a placeholder that cannot be specified.
source to share