Álvaro Ruiz
Álvaro Ruiz

Reputation: 239

Java Collection methods

I'm starting to learn Java and I have a question about generics.

In this methods from Collection<E> interface:

boolean containsAll( Collection <?> c);
boolean removeAll(Collection<?> c);
boolean retainAll ( Collection <?> c);

Why is the parameter Collection <?> c instead of Collection <E> c?

Thanks a lot

Upvotes: 3

Views: 328

Answers (2)

millimoose
millimoose

Reputation: 39950

The JDK designers wanted code like the following to be possible:

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 might not exactly compile because I can't remember how Arrays.asList() captures type parameters, but it should get the point across.)

That is, because you can call .equals() on any pair of objects and get a meaningful result, you don't really need to restrict those methods to a specific item type.

Upvotes: 2

Jack
Jack

Reputation: 133567

Because a E type parameter needs to be specified while a wildcard ? works for every type. The subtle difference is that

  • E means any specified type
  • ? means any unknown type

Since there methods are supposed to work on a collection of any unknown type then they doesn't specify a type parameter at all. E is a type variable. ? is not a variable, is a placeholder which cannot be specified.

Upvotes: 2

Related Questions