Generic

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

  1. The user can’t apply the basic type to the generic type;
  2. The generic can’t be constructed ;
  3. The generic cant’t be modified by static;
  4. The generic can’t be converted by type convertor;
  5. The instance of can’t be apply to check the generic type;
  6. The generic type array can’t be constructed;
  7. The generic exception can’t be defined.
  8. The generic type can’t be overloaded.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值