Generic
What is Generic?
Params are genericed. In order to implment generic, the java developer user type erasure to be compatible with the previous version of jdk. Therefor, the generic is not real generic. For example, List<Integer>
and List<String>
are different in the complier period and are the same in the running time.
Types of Generic
Generic Class(generally speaking, outer class)
Definition
permission-modifies class className<generic type>{
}
Generic Interface
Definition
permission-modifies interface interfaceName<generic type>{
}
PS:class implements interface
permission-modifies class className<generic type> implements interfaceName<generic type>{
}
permission-modifies class className implements interfaceName<real type>{
}
Generic Method
Definition
permission-modifies modifies <generic type> returnType methodName(T param, ....){
}
Generic wildcard (?)
Using genreic wildcard can accept any type. However, the get and add methods are not able to used for the wildcard.
Supplment: Although, the get method is appropriate for the generic wildcard except :
Object o = list.get(0);
the add method is appropriate for the generic wildcard except:
list.add(null);
Generic upper bound
permission-modifies class className<generic type super A>{
}
Generic lower bound
permission-modifies class className<generic type extends A & B &.....>{
}
PS: Using generic upper and lower bounds follows PECS(Producer extends Consumer super) principle.
public void <List<? extends A> producerA, List<? super A> consumerA{
for(int i = 0; i < producerA.size(); i++){
consumerA.add(producerA.get(i));
}
}
Limits of Generic
- The user can’t apply the basic type to the generic type;
- The generic can’t be constructed ;
- The generic cant’t be modified by static;
- The generic can’t be converted by type convertor;
- The instance of can’t be apply to check the generic type;
- The generic type array can’t be constructed;
- The generic exception can’t be defined.
- The generic type can’t be overloaded.