泛型 Generic
DEFINITION AND COMPREHENSION:泛型是程序设计语言的一种特性。允(run or yun HA!)许程序员在强类型程序设计语言中编写代码时定义可变类型参数,泛型是将类型参数化而提高代码复用率的一种数据类型。
对于JAVA和C#语言来说假如没有泛型这个概念,当在程序某处我们需要一个参数而我们不确定我们会得到什么类型的参数的时候,做为单根继承机制的语言来说我们可以在此处使用Object类型,example:
1 public class ObjectParameter{ 2 private Object temp; 3 public ObjectParameter(Object temp){ 4 this.temp = temp; 5 } 6 public void set(Object temp){ 7 this.temp = temp; 8 } 9 public Object get(){ 10 return temp; 11 } 12 13 //创建实例,然后通过构造方法和get方法将String类型和int类型传给temp 14 public static void Main(String[] args ){ 15 ObjectParameter op = new ObjectParameter("HELLO"); 16 System.out.print(op.get()); 17 18 op.set(10); 19 System.out.print(op.get()); 20 21 // ... 22 } 23 24 }
as you see,在set方法你可以传入任何类型的参数,而get方法返回的值的具体类型我们却不清楚,运行中的程序在此处就有可能引发不可预见的异常,而且这里也会引起装箱和拆箱过程,所以这种方式不是高性能的选择。下面我们看泛型版本,example:
1 class GenericClass{ 2 private String temp; 3 GenericClass(String temp){ 4 this.temp = temp; 5 } 6 public String get(){ 7 return temp; 8 } 9 } 10 11 public class ObjectParameter<T>{ 12 private Ttemp; 13 public ObjectParameter(T temp){ 14 this.temp = temp; 15 } 16 public void set(T temp){ 17 this.temp = temp; 18 } 19 public T get(){ 20 return temp; 21 } 22 23 // 24 public static void Main(String[] args ){ 25 ObjectParameter<GenericClass> op = new ObjectParameter(new 26 GenericClass("Hello Generic!")); 27 System.out.print(op.get()); 28 29 //op.set(10); ERROR 30 //System.out.print(op.get()); 31 32 // ... 33 } 34 35 } 36 37
当你试图通过op.set(10)将10穿入的时候就会产生错误,从而保证了类型安全性。
Again for instance, 当你设计算法的时候,要想将算法适用于多种数据类型,就需要为每种数据类型设计一个类来使用这种方法,这将增加你的代码编写量同时也降低代码可复用性,But Generic can solve your this problem!
而事实上泛型也多是用在容器中,我们使用的框架已经为我们设计了好了泛型版本的容器,所以我们经常不需要自己去设计泛型类