Search code examples
javagenericsbounded-wildcard

Why no bounded wildcard in input parameters of synchronizedCollection() static factory method?


I was going through the Java tutorial and stumbled on something which I did not understand. In the Collections trail, they talk about Wrapper implementations, there I notice two static factory methods -

public static <T> Collection<T> synchronizedCollection(Collection<T> c);

public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c);

I am wondering why does synchronized wrappers don't use bounded wildcards? i. e. Why is the signature of synchronizedCollection not the following?

public static <T> Collection<T> synchronizedCollection(Collection<? extends T> c);

Solution

  • Collection<? extends T> c with that you can only get stuffs but cannot add to it, which makes sense in case of unmodifiableCollection, for the method the argument should only act as producer. But in case of synchronizedCollection, it's synchronized but still modifialbe, it should also be able to add and remove, so it has to be Collection<T> c, it should act as both producer and consumer.

    This might be helpful to know about What is PECS (Producer Extends Consumer Super)?