Generics (1)

This series are all coming from Java Generics and Collections . This book is the one I wish I read it a few years ago.

 

Basic Concept

 

We say that generics are implemented by erasure because the types List<Integer>, List<String> and List<List<String>> are all represented at run-time by the same type, List . We also use erasure to describe the prococess that converts the generic program to the non-generics program. The term erasure is a slight misonmer, since the process erasure type parameters but adds casts.

 

Generics implicitly perform the same cast that is explicitly performed without generics. If such casts could fail, it might be hard to debug code written with generics. This is why it is reassuring that generics come with the following guarantee:
Cast-iron guarantee: the implicit casts added by the compilation of generics never fail.

Implementing generics by erasure has a number of important effects. It keeps things simple, in that generics do not add anything fundamentally new. It keeps things small, in that there is exactly one implementation of List , not one version for each type. And it eases evolution, since the same library  can be accessed in both nongeneric and generic forms.

 

This last point is worth some elaboration. It means that you don't get nasty problems due to maintaining two versions of the libraries: a nongeneric legacy version that works with Java 1.4 or earlier, and a generic version that works with Java 5 and 6. At the bytecode level, code that doesn't use generics looks just like code that does. There is no need to switch to generics all at onceyou can evolve your code by updating just one package, class, or method at a time to start using generics. We even explain how you may declare generic types for legacy code.

 

Generic Method and Varargs

 


A method which declares a type variable in this way is called a generic method. The scope of the type variable T  is local to the method itself; it may appear in the method signature and the method body,  but not outside the method.
 
The vararg feature permits a special, more convenient syntax for the case in which the last argument of a method is an array.
 
When a type parameter is passed to a generic method invocation, it appears in angle brackets  to the left, just as in the method declaration. The Java grammar requires that type parameters may appear only in method invocations that use a dotted form.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值