I'm currently reading Java Generics, and I am a bit stuck when it comes to Wildcards.
I have been given this method from the Collections class:
public void <T> copy(List<? super T> dest, List<? extends T> src) {
for(int i = 0; i < src.size(); i++) {
dest.set(i, src.get(i));
}
}
I have then been told that it is possible to call the method like this:
List<Object> objs = new ArrayList<Object>();
List<Integer> ints = new ArrayList<Integer>();
Collections.copy(objs, ints);
As the type parameter has been left to the compiler to determine, the book says the compiler chooses the type parameter to be Integer.
But how is that possible?
If it were taken to be Integer, this would mean that in the method declaration -List<? extends T>
would translate to List<Integer extends Integer>
.
Is this a mistake, or are there different rules when regarding Generics? I have googled around and the majority of results say that a class cannot be a subclass of itself.
Non-generic class can't extend generic class except of those generic classes which have already pre defined types as their type parameters.
Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.
Generic classes support an inheritance mechanism and can form hierarchies. Any generic class that takes a type T as a parameter can be inherited by another derived class. In this case, a parameter of type T is passed to the derived class.
Using generics, primitive types can not be passed as type parameters. In the example given below, if we pass int primitive type to box class, then compiler will complain. To mitigate the same, we need to pass the Integer object instead of int primitive type.
No, it's not an error.
? extends Integer
means: any class that is or extends Integer (or implements Integer, if Integer was an interface).
The same goes for ? super Integer
, which means: any class that is Integer or is a superclass or super-interface of Integer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With