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.
本文深入解析Java泛型的概念,包括泛型类、泛型接口、泛型方法等的定义与使用,探讨类型擦除对泛型的影响,以及泛型通配符、上下界限制的应用,并指出泛型使用的限制。

1702

被折叠的 条评论
为什么被折叠?



