<aside>
💡 If S is compatible with T, S[]
is compatible with T[]
</aside>
Example
ETicket[] etktarr = new ETicket[10];
Ticket[] tktarr = etktarr;
// Valid since ETicket is a subtype of Ticket
But now:
tktarr[5] = new Ticket()
//Invalid -> tktarr[5] refers to an ETicket and you trying to store Ticket which does not support all functionalities of ETicket.
Thus
<aside> 💡 Java array typing is Covariant.
</aside>
S[]
extends T[]
Now, Generic classes are not Covariant.
LinkedList<String>
is not compatible with LinkedList<Object>
.The following will not work to print out an arbitrary LinkedList
public class LinkedList<T>{...}
public static void printlist(LinkedList<Object> l){
Object o;
Iterator i = l.get_iterator();
while(i.has_next()){
o = i.get_next();
System.out.println(o);
}
}
LinkedList
of type Object
and not any other type.Solution: Make the above method generic by introducing type variable:
public class LinkedList<T> { ... }
public static <T> void printlist(LinkedList<T> l){
Object o;
Iterator i = l.get_iterator();
while(i.has_next()){
o = i.get_next();
System.out.println(o);
}
}
Object o
instead of T o
also as above.Note that we are not using T
anywhere inside our function → Instead we use Object o
Instead of using T
we can just use a wildcard ?
as a type variable above.
public class LinkedList<T>{ ... }
public static void printlist(LinkedList<?> l){
Object o;
Iterator i = l.get_iterator();
while(i.has_next()){
o = i.get_next();
System.out.println(o);
}
}
?
→ Arbitrary Unknown TypeWe can define variables of the wildcard type(Only define the variable→ Cannot assign a new object of type ?
):
public class LinkedList<T>{ .. }
LinkedList<?> l; # LinkedList l of arbitrary type.