Question about Java generics and design of java.util.function.Function - java

question about Wildcard
Example:Student extends Person
Person person = new Person();
Student student = new Student();
List<? super Student> list = new ArrayList<>();
list.add(student); // success
list.add(person); // compile error
List<? extends Person> list2 = new ArrayList<>();
list2.add(person); // compile error
list2.add(student);// compile error
I have read the answer below a question "capture#1-of ? extends Object is not applicable"
You are using generic wildcard. You cannot perform add operation as class type is not determinate. You cannot add/put anything(except null) -- Aniket Thakur
Official doc:The wildcard is never used as a type argument for a generic method invocation, a generic class instance creation, or a supertype
But why could list.add(student) compile successfully ?
Design of java.util.function.Function
public interface Function<T, R>{
//...
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
}
Why before is designed to Function<? super V, ? extends T> rather than Function<V,T> when the type of return is Function<V,R> and type of the input is V ? (It still can pass compile and use flexibly)

To understand these questions, you have to understand how generics work with subtyping (which is explicitly denoted in Java using the extends keyword). Andreas mentioned the PECS rules, which are their representations in Java.
First of all, I want to point out that the codes above can be corrected by a simple cast
ArrayList<? super Student> list = new ArrayList<>();
list.add(new Student());
ArrayList<Person> a = (ArrayList<Person>) list; // a covariance
a.add(new Person());
And compiles & runs well (rather than raising any exceptions)
The reason is simple, when we have a consumer (which takes some objects and consume them, such as the add method), we expect it to take objects of type no more than(superclasses) the type T we specified, because the process of consuming needs possibly any member(variables, methods etc.) of the type it wants, and we want to ensure that type T satisfy all the members the consumer requires.
On the contrary, a producer, which produces objects for us (like the get method), has to supply objects of type no less than the specified type T so that we can access any member that T has on the object produced.
These two are closely related to subtyping forms called covariance and contravariance
As for the second question, you can refer to the implementation of Consumer<T> as well (which is somewhat simpler):
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
the reason why we need this ? super T is that: when we are combining two Consumers using the method andThen, suppose that the former Consumer takes an object of type T, we expect the later to take a object of type no more than T so it would not try to access any member that T doesn't have.
Therefore, rather than simply writing Consumer<T> after but Consumer<? super T> after, we allow the former consumer (of type T) to be combined with a consumer that takes an object not exactly of type T, but maybe smaller then T, by the convenience of covariance. That makes the following codes sound:
Consumer<Student> stu = (student) -> {};
Consumer<Person> per = (person) -> {};
stu.andThen(per);
The compose method of type Function also applies, by the same consideration.

IMO This is probably the most complex concept in vanilla Java. So let's break this down a bit. I'll start with your second question.
Function<T, R> takes an instance t of type T and returns an instance r of type R. With inheritance that means that you could supply an instance foo of type Foo if Foo extends T and similarly return bar of type Bar if Bar extends R.
As a library maintainer who wants to write a flexible generic method, it's hard, and actually impossible, to know in advance all the classes which might be used with this method which extend T and R. So how are we going to write a method that handles them? Further, the fact that these instances have types which extend the base class is none of our concern.
This is where the wildcard comes in. During the method call we say that you can use any class which meets the envelope of the required class. For the method in question, we have two different wildcards using upper and lower bounded generic type parameters:
public interface Function<T, R>{
default <V> Function<V, R> compose(Function<? super V, ? extends T> before)
Lets now say that we want to take advantage of this method... for the example lets define some basic classes:
class Animal{}
class Dog extends Animal{}
class Fruit{}
class Apple extends Fruit{}
class Fish{}
class Tuna extends Fish{}
Imagine our function and transformation is defined as below:
Function<Animal, Apple> base = ...;
Function<Fish, Animal> transformation = ...;
We can combine these functions using compose to create a new function:
Function<Fish, Apple> composed = base.compose(transformation);
This is all fine and dandy, but now imagine that in the desired output function we actually only want to use Tuna as the input. If we did not use the lower-bounded ? super V as the input type parameter for the Function we pass to compose then we would get a compiler error:
default <V> Function<V, R> compose(Function<V, ? extends T> before)
...
Function<Tuna, Apple> composed = base.compose(transformation);
> Incompatible types:
> Found: Function<Fish, Apple>, required: Function<Tuna, Apple>
This happens because the return type for the call to compose specifies V as Tuna while transformation on the other hand specifies its "V" as Fish. So now when we try to pass transformation to compose the compiler requires transformation to accept a Tuna as its V and of course Tuna does not identically match Fish.
On the other hand, the original version of the code (? super V) allows us to treat V as a lower bound (i.e. it allows "contravariance" vs. "invariance" over V). Instead of encountering a mismatch between Tuna and Fish the compiler is able to successfully apply the lower bound check ? super V which evaluates to Fish super Tuna, which is true since Tuna extends Fish.
For the other case, imagine our call is defined as:
Function<Animal, Apple> base = ...;
Function<Fish, Dog> transformation = ...;
Function<Fish, Apple> composed = base.compose(transformation);
If we did not have the wildcard ? extends T then we would get another error:
default <V> Function<V, R> compose(Function<? super V, T> before)
Function<Fish, Apple> composed = base.compose(transformation);
// error converting transformation from
// Function<Fish, Dog> to Function<Fish, Animal>
The wildcard ? extends T allows this to work as T is resolved to Animal and the wildcard resolves to Dog, which can satisfy the constraint Dog extends Animal.
For your first question; these bounds really only work in the context of a method call. During the course of the method, the wildcard will be resolved to an actual type, just as ? super V was resolved to Fish and ? extends T was resolved to Dog. Without the information from the generic signature, we would have no way for the compiler to know what class can be used on the type's methods, and therefore none are allowed.

Related

Java Function interface with bounded wildcard

I'm trying to use java.util.Function object as an input to a library class.
Function<? extends MyEntity, List> mapper;
public MyLibraryClass(Function<? extends MyEntity,List> mapper) {
...
}
public void aMethod(ClassExtendsMyEntity e) {
mapper.apply(e);
}
The line mapper.apply(e) doesn't compile.
If I change to use ? super instead of ? extends, then the fail will be in the client using this library in the following code:
Function<ClassExtendsMyEntity, List> mapper = e -> e.getListObjects();
new MyLibraryClass(mapper);
Can anyone help explain why getting this issue and if there is a way to get this working?
Function<? extends MyEntity,List> mapper;
This does not say "any subclass of MyEntity can be passed to mapper". It says "there exists some subclass of MyEntity that can be passed to mapper". It might be ClassExtendsMyEntity, it might be MyEntity itself, or it might be some crazy class that you've never even heard of.
Function<T, S> provides one function: S apply(T arg). Since your argument type is ? extends MyEntity, the only valid argument you can pass to mapper.apply is a value which is of every subtype of MyEntity at once, and there is no value that satisfies that condition.
Put more technically, the first argument of Function<T, S> is, in principle, contravariant, so using the covariant ? extends T annotation makes little sense on it.
Depending on what you want, there are two solutions. If your function works for any MyEntity, then you should simply write Function<MyEntity, List> and forgo the generics/wildcards altogether. On the other hand, if you want MyLibraryClass to support only one subtype, but a subtype that you know about, then you need to make that a generic argument to MyLibraryClass.
public class MyLibraryClass<T extends MyEntity> {
Function<? super T, List> mapper;
public MyLibraryClass(Function<? super T, List> mapper) {
...
}
public void aMethod(T e) {
mapper.apply(e);
}
}
Again, the first type argument of Function is, in principle, contravariant, so we should use ? super T to bound it by our type argument T. That means that if I have a MyLibraryClass<ClassExtendsMyEntity>, the function inside that might be a Function<ClassExtendsMyEntity, List>, or a Function<MyEntity, List>, or a Function<Object, List>, since all of those support ClassExtendsMyEntity arguments. For more on the reasoning behind that, see What is PECS.
The declaration Function<? extends MyEntity,List> mapper means:
mapper expects an argument of some type X which is a subtype of MyEntity. The problem is, it doesn't tell what type it is.
And therefore the compiler can't verify if your call passing an instance of type ClassExtendsMyEntity is valid. After all X might be SomeOtherClassExtendingMyEntity.
In order to fix this just make the function type Function<MyEntity,List>

Why is Predicate<? super SomeClass> not applicable to Object?

Assume we have a predicate declared as Predicate<? super SomeClass>. I would naively expect it to be applicable to any superclass of SomeClass up the hierarchy, including Object.
However this predicate is not applicable to Object. I get the following error:
The method test(capture#3-of ? super SomeClass) in the type Predicate is not applicable for the arguments (Object)
Demo.
Why is Predicate<? super SomeClass> not applicable to an instance of Object?
The code:
import java.util.*;
import java.lang.*;
import java.io.*;
import java.net.URL;
import java.util.function.Predicate;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Predicate<? super URL> p = u -> u.getFile().isEmpty();
p.test(new Object());
}
}
For a Predicate<? super SomeClass> variable, you can assign a Predicate<SomeClass> instance, or a Predicate<Object> instance.
However, you can't pass an Object to the test() method of a Predicate<SomeClass>. You can only pass a SomeClass instance.
Therefore you can't pass an Object to the test() method of a Predicate<? super SomeClass>
Consider the following:
Predicate<URL> p1 = u -> u.getFile().isEmpty();
Predicate<? super URL> p2 = p1;
p2 is referring to a Predicate<URL>, so you can't pass a new Object() to its test() method.
In other words, in order for p.test(new Object()) to be accepted by the compiler, it must be valid for any Predicate that can be assigned to the Predicate<? super URL> p variable. Since the Predicate<URL> Predicate can be assigned to that variable, and its test() method cannot accept an Object, p.test(new Object()) cannot be accepted by the compiler.
BTW, in your specific example, you are creating a Predicate<URL>, and URL is a final class. Therefore, you should simply declare it as:
Predicate<URL> p = u -> u.getFile().isEmpty();
There's no reason for ? super or ? extends.
Consider the broader example:
Predicate<? super Integer> p;
In this situation, any of the following assignments is valid, right?
p = (Predicate<Integer>) i -> true; // but, only Integer can be applied
p = (Predicate<Number>) n -> true; // Number and its sub-classes (Integer, Double...)
p = (Predicate<Object>) o -> true; // any type
So, if in the end it is:
Predicate<? super Integer> p = (Predicate<Integer>) i -> true;
Then, certainly, neither Number nor Object could not be applied to the predicate.
To guarantee type safety, a compiler allows only those types, which are valid for any of the possible assignments to the Predicate<? super Integer> - so, only Integer in this particular example.
Changing the lower bound from Integer to Number extends the boundaries respectively:
Predicate<? super Number> p = (Predicate<Number>) n -> true;
Now, the predicate can be applied to the Number and any of its sub-classes : Integer, Double etc.
Summarizing
The only types which can be applied to the Predicate<? super SomeClass> without breaking a type safety guarantees: the lower bound itself and its sub-classes.
The Predicate already has a type. The type the predicate accepts can't be decided at the point when you try and call it. It has a type, and that type is some superclass of X; it's just unknown.
If I have a Predicate<Collection>, that could be referenced as a Predicate<? super List>. But that doesn't mean that it will accept any Object. The ? extends X generic type doesn't mean it will accept anything matching the given constraints. It means it is a predicate for some kind of unknown type that matches the given constraints.
Predicate<? super List> predicate = Collection::isEmpty;
predicate.test(new Object()); // Should this be valid? Clearly not
The java tutorial pages provides some good information about upper / lower bounded wildcards when using generics.
It also provides some guidelines for using wildcards which can help decide which wildcard you should use:
An "In" Variable
An "in" variable serves up data to the code. Imagine a copy method with two arguments: copy(src, dest). The src argument provides the
data to be copied, so it is the "in" parameter. An "Out" Variable
An "out" variable holds data for use elsewhere. In the copy example, copy(src, dest), the dest argument accepts data, so it is the
"out" parameter.
Of course, some variables are used both for "in" and "out" purposes —
this scenario is also addressed in the guidelines.
You can use the "in" and "out" principle when deciding whether to use
a wildcard and what type of wildcard is appropriate. The following
list provides the guidelines to follow: Wildcard Guidelines:
An "in" variable is defined with an upper bounded wildcard, using the extends keyword.
An "out" variable is defined with a lower bounded wildcard, using the super keyword.
In the case where the "in" variable can be accessed using methods defined in the Object class, use an unbounded wildcard.
In the case where the code needs to access the variable as both an "in" and an "out" variable, do not use a wildcard.
These guidelines do not apply to a method's return type. Using a
wildcard as a return type should be avoided because it forces
programmers using the code to deal with wildcards.
This is quite a complex subject. These ? extends T and ? super T declarations are rather supposed to create a "matching" between classes.
If a class defines a method taking a Consumer, say something like Iterable<T>.foreach(), it defines this consumer to accept everything which can take a T. Thus, it defines it as forEach(Consumer<? super T> action). Why? Because an Iterator<Integer>'s foreach() can be called with a Consumer<Number> or even a Consumer<Object>. This is something which wouldn't be possible without the ? super T.
OTOH, if a class defines a method taking a Supplier, say something like addFrom, it defines this supplier to supply everything which is a T. Thus, it defines it as addFrom(Supplier<? extends T> supplier). Why? Because a ThisClass<Number>'s addFrom() can be called with a Supplier<Integer> or a Supplier<Double>. This is something which wouldn't be possible without the ? extends T.
Maybe a better example for the latter: List<E>.addAll() which takes a Collection<? extends E>. This makes it possible to add the elements of a List<Integer> to a List<Number>, but not vice versa.

Java API class having a method with a meaningless type wildcard

In Java 8, the class java.util.Optional (javadoc) class offers functionality of the "Maybe" Monad or the Option Type.
More directly:
public final class java.util.Optional<T> extends Object
A container object which may or may not contain a non-null value. If a
value is present, isPresent() will return true and get() will return
the value.
One of the methods is:
<U> Optional<U> map(Function<? super T,? extends U> mapper)
If a value is present, apply the provided mapping function to it, and if
the result is non-null, return an Optional describing the result.
The question is simply why does map() use a type wildcard on the U type.
My understanding of type wildcarding is simply that:
? super T designates some type from the set of classes given by the subclassing path from Object to T (both Object and T included) union the set of interfaces found on any subinterfacing path pulled in "as a sidedish" via implements.
And ? extends U simply designates some type from the set of classes that extend U (Uincluded).
So one could just write:
<U> Optional<U> map(Function<? super T,U> mapper)
without loss of information.
Or not?
Not quite.
A Function<? super T, U> is not the same as a Function<? super T, ? extends U>.
For example, I could still get an Optional<CharSequence>, even if I passed a Function<Object, String> to the method. If the method was defined as <U> Optional<U> map(Function<? super T, U> mapper), then this would not be possible.
That is because generics are invariant: <T> is not the same as <? extends T>. That's a design decision implemented in the Java language.
Let's see how Jon Skeet explains what would happen if generics would not be invariant:
class Animal { }
class Dog extends Animal { }
class Cat extends Animal { }
public void ouch() {
List<Dog> dogs = Arrays.asList(new Dog(), new Dog());
List<Animal> animals;
// This would be legal, right? Because a list of dogs is a list of animals.
List<Animal> animals = dogs;
// This would be legal, right? Because a cat could be added to a
// list of animals, because a cat is an animal.
animals.add(new Cat());
// Unfortunately, we have a confused cat.
}
Although I'm not entirely sure what you mean in your comments, I'll try to elaborate.
If you have full control over the Function you provide, it doesn't matter whether the method's signature is Function<? super T, U> or Function<? super T, ? extends U>, you'll just adapt your Function accordingly. But the authors of the method probably wanted the method to be as flexible as possible, allowing one to provide a Function with its second parameter to be also a subclass of U, instead of only U itself. Actually you widen its lower bound from U to a certain subtype of U.
So the function should really read <U> Optional<? the-most-general-but-fixed-supertype-of U> map(Function<? super T, U> mapper) but expressing it that way would be awkward.
I would be indeed awkward. In addition, there is a difference between your proposed notation and the actual method signature of map(), which involve implications of lower bounds and upper bounds.
Read more:
A picture explaining the principle "Producer Extends Consumer Super"
What is the use of saying <? extends SomeObject> instead of <SomeObject>?
Upper and lower bounds

Why is it not possible to pass a <?> or a <? extends T> generic class instance to a method expecting a <? super T>?

The PECS principle is about what kind of argument you select in a function, depending on how you will use that parameter.
My question is about the fact that, once you chose to use super (because your function possibly is a Consumer), you cannot pass to that function certain generic class instances.
Let's consider the following program:
public class Main{
public static void main(String[] args){
List<?> unbound = new ArrayList<Long>();
List<? extends Long> extendsBound = new ArrayList<Long>();
List<? super Long> superBound = new ArrayList<Long>();
takeExtend(unbound);
takeExtend(extendsBound);
takeExtend(superBound);
takeSuper(unbound);
takeSuper(extendsBound);
takeSuper(superBound);
}
static <T> void takeExtend(List<? extends T> l){}
static <T> void takeSuper(List<? super T> l){}
}
The compiler gives the following error:
error: method takeSuper in class Main cannot be applied to given
types;
takeSuper(unbound);
^ required: List<? super T> found: List<CAP#1> reason: cannot infer type-variable(s) T
(argument mismatch; List<CAP#1> cannot be converted to List<? super T>) where T is a type-variable:
T extends Object declared in method <T>takeSuper(List<? super T>) where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ?
I was trying to find a sort of symmetry, such as the one we have for the PECS rule, but I didn't find any.
So:
Why is it not possible to pass a <?> or a <? extends T> to a function expecting <? super T>?
Why is it possible to pass a <?> to a function expecting a <? extends T>?
Why is it possible to pass a <? super T> to a function expecting a <? extends T>?
You can think of a generic method (i.e. a method with its own type parameters) as making a set of statements about its type parameters.
For example, the method <T> someMethod(List<T>) is saying:
There exists some type T for which the type parameter of this list equals T.
Easy. All lists fit this criterion, so any list is a valid input to the method.
Everything inside the method can now make use of the knowledge that that statement is true. How is that knowledge useful? Well, if we get an item from the list, we know it matches the list's type parameter. Because we captured the type as T, we can hold a reference to the object and put it back in the list later, all still without knowing what type it really is.
The method declaration <T> someMethod(List<? extends T>) makes a slightly different claim:
There exists some type T for which the type parameter of this list is a subtype of T.
This is also trivially true for all lists. However, you might notice that it makes <T> someMethod(List<? extends T>) a bit useless. You're telling the compiler to capture the fact that items that come out of the list share some common supertype with other items that come out of the list. Unless you have, inside the method, some other consumer that is known to accept <? super T>, there's nothing you can do with that information. It's much less useful than the knowledge that all the items that come from the list are of the same type.
So, why doesn't <T> takeSuper(List<? super T>) work the same way?
The method declaration <T> takeSuper(List<? super T>) can be interpreted as claiming that:
There exists some type T for which the type parameter of this list is a supertype of T.
If we have a List<? super Long> and we pass it to a method that captures <T> takeSuper(List<? super T>) it's easy to see that a reference of type Long would satisfy T. We could pass a Long to the method as a parameter of type T, and then add it to the list from inside the method.
But what about if we have a List<?> and we capture its type using the method <T> takeSuper(List<? super T>)? By declaring the list as a List<?> we're saying that we don't currently know what its type parameter is. In doing that, we're telling the compiler that we have absolutely no way to get a reference of a type that matches the type parameter of the list. In other words, the compiler knows with certainty that no object can satisfy the type parameter T. Remember, for this method, an object is of type T if it is known to be of a type that is a subtype of the type parameter of the list. If we don't know anything about the type parameter of the list, that's impossible.
The same is true for a List<? extends Long>. We know that the items we fetch from the list will be a subtype of Long, but we don't have a lower bound for their type. We can never prove that any type is a subtype of the list's type parameter. So, for the method <T> takeSuper(List<? super T>), there is again provably no way to get a reference of type T.
Interestingly, my compiler (Java 8) doesn't complain about calling the method <T> takeSuper(List<? super T>) with a List<?> as input. I suppose it recognizes that since there's no way to get a reference of type T, there's no harm in just ignoring the useless type parameter.
Why is it not possible to pass a <?> or a <? extends T> to a function expecting <? super T>?
Consider this method:
static <T> void sillyAdd(List<? super T> l, T t){
l.add(t);
}
Now look how we could use it if this were possible:
List<Integer> onlyIntegers = new ArrayList<>();
List<? extends Number> anyNumber = onlyIntegers;
sillyAdd(anyNumber, Float.valueOf(0)); /* Not allowed... */
Integer i = onlyIntegers.get(0);
The last line would throw a ClassCastException because we were allowed to put a Float into a List<Integer>.
Why is it possible to pass a <?> to a function expecting a <? extends T>?
takeExtend(unbound);
There are no bounds on T; it could be any type. While the type parameter of unbound is unknown, it does have some type, and since T can be any type, it's a match.
Methods like this are sometimes used as a helper in some odd corners of generics. Logically, we know that the following should be no problem:
public static void rotate(List<?> l) {
l.add(l.remove(0));
}
But the rules of generics don't imply type-safety here. Instead, we can use a helper like this:
public static void rotate(List<?> l) {
helper(l);
}
private static <T> void helper(List<T> l) {
l.add(l.remove(0));
}
Why is it possible to pass a <? super T> to a function expecting a <? extends T>?
It's not, in a way. Given this example:
static <T> void takeExtend(List<? extends T> l)
List<? super Long> superBound = new ArrayList<Long>();
takeExtend(superBound);
You might think that T is inferred to be Long. That would mean that you passed a List<? super Long> to a method declared like void takeExtend(List<? extends Long> l), which seems wrong.
But T isn't inferred to be Long. If you specify Long explicitly as the type parameter, you'll see that it won't work:
Main.<Long>takeExtend(superBound);
What's actually happening is that T is inferred to be ? super Long, so the generic type of the method is something like void takeExtend(List<? extends ? super Long>). That means that everything in the list is something that extends an unknown super class of Long.
Why is it not possible to pass a <?> or a <? extends S> to a function expecting <? super T>? (Question corrected for clarity: ? extends S).
The compiler wants to infer the T, which is the bottom limit, and it can't. Every class extends Object, but there is no universal inheritance tree bottom class, which the compiler could default to.
Why is it possible to pass a <?> to a function expecting a <? extends T>?
It's about inference. You can pass a <?> because the compiler can make something out of it. Namely, it can make Object out of T. The same happens with the following:
List<?> unbound = new ArrayList<>();
Why is it possible to pass a <? super T> to a function expecting a <? extends T>?
Again, it's about inferring the upper limit now, so the compiler can default to Object. It's not interested in what ? is super to, nor whether it is super to anything at all.
I've been thinking this stuff all night long, with the amazing help of your comments, trying to find an easy-to-remember solution.
This is what I got.
A method accepting a <? extends T>, to get T, must infer the upper limit of that hierarchy. Since in Java every class is extending Object, the compiler can rely on the fact that at least the upper limit is Object. So:
if we pass a <? extends T>, the upper bound is already defined and it
will use that one
if we pass <?>, we don't know anything, but we know
that every class extends Object, so the compiler will infer Object
if we pass <? super T>, we know the lower bound, but since every class
extends Object, the compiler infer Object.
A method accepting a <? super T>, to get T, must infer the lower limit of that hierarchy. In Java by default we can count on an upper bound, but not on a lower bound. So the considerations made in the previous case are not valid anymore. So:
if we pass a <? extends T>, there is no lower bound, because the
hierarchy can be extended as much as we want
if we pass a <?>,
there is no lower bound, because the hierarchy can be extended as
much as we want
if we pass a <? super T>, a lower bound is already
defined, so we can use that one.
Recapping:
a method accepting a <? extends T> can always rely on the fact that
an upper bound exists and that is Object -> we can pass every bound to it
a method accepting a <? super T> can infer a lower bound only if it is explicitly defined in the parameter -> we can only pass a <? super T>

Bounded generic method not compiling - why?

The code below makes complete sense to me - its about adding an element of some type which is supertype of type T and type S is definitely such a super type , so why the compiler refuses to add 'element' into the collection ?
class GenericType<S,T extends S>{
void add1(Collection<? super T> col ,S element ){
col.add(element); // error
// The method add(capture#9-of ? super T) in the type
// Collection<capture#9-of ? super T> is not applicable for the arguments (S)
}
}
Thake an example, if A <- B <- C where <- means that is the supertype, then if S = B and T = C you cannot add an instance of S to a collection of T.
A supertype of T may be the supertype or a subtype of another supertype of T (in this case S).
Collection<? super T> does not mean "a collection that can contain T and any superclass of it" - it's actually not possible to formulate that restriction. What it means is "a collection that can only contain instances of some specific class which is a superclass of T" - basically it ensures that you can add a T to the collection.
The method can be called with a Collection<T>, yet you want to add an S to it.
new GenericType<Object,Integer>().add1(new ArrayList<Integer>(), "");
You are trying to put an element of type S into a collection of type T. Generics aren't polymorphic.
You have to take notice of 2 problems here. you are trying to create an Collection of type concreteObject extends Object and are adding an object
So when you have
Car extends Vehicle{}
ElectricCar extends Car{}
you are trying to do
Collection<? extends Car> collection;
collection.add(new Vehicle());
The second problem lies with the non-polymorphism nature of Generics. See this great explanation -> Is List<Dog> a subclass of List<Animal>? Why aren't Java's generics implicitly polymorphic?

Categories

Resources