Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics - Class a Subclass of itself?

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.

like image 338
user3650602 Avatar asked Dec 23 '15 18:12

user3650602


People also ask

Can a generic class be a subclass of a non generic class?

Non-generic class can't extend generic class except of those generic classes which have already pre defined types as their type parameters.

How can we restrict generic to a subclass of particular class?

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.

Can generic classes be inherited?

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.

Can generics be primitive types?

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.


1 Answers

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.

like image 193
JB Nizet Avatar answered Oct 17 '22 04:10

JB Nizet