泛型设计中<T> 和<E>的区别

Java中泛型有泛型类和泛型方法

-----------------------------------------------

// 泛型方法

用E表示时,意思是element的意思,表示方法中的参数类型

 1 package com.wang.practice;
 2 
 3 public class TestGenerics01{
 4 
 5     /**
 6      * 泛型例子 ---泛型方法
 7      * @param args
 8      */
 9     public static <T> void printArray(T[] array){
10         for (T element : array) {
11             System.out.printf("%s",element);
12             System.out.printf("  ");
13         }
14         System.out.println();
15     }
16     
17     
18     public static void main(String[] args) {
19         Integer[] array1 = {1,2,3,4,5,6};
20         Double[] array2 = {1.2,3.3,4.3,2.3,2.1};
21         Character[] array3 = {'a','v','c'};
22         
23         printArray(array1);
24         printArray(array2);
25         printArray(array3);
26         
27     }
28 
29 }

----------------------------------------------

//泛型类

用T表示时,意思是Type的意思,用来表示类的参数类型

 1 package com.wang.practice;
 2 
 3 public class TestGenerics<T> {
 4 
 5     /**
 6      * 泛型类
 7      * @param args
 8      */
 9     private T t;
10     
11     public T getT() {
12         return t;
13     }
14     
15     public void setT(T t) {
16         this.t = t;
17     }
18 
19     public static void main(String[] args) {
20         TestGenerics<Integer> integerBox = new TestGenerics<>();
21         TestGenerics<String> stringBox = new TestGenerics<>();
22         
23         integerBox.setT(new Integer(10));
24         stringBox.setT(new String("kjlkjl"));
25         
26         System.out.printf("整型值为:%d

",integerBox.getT());//换行两行
27         System.out.printf("字符串为:%s",stringBox.getT());
28     }
29 }

总结:其实不管T还是E,仅仅只是一个习惯而已,用什么起的作用是一样的。

另外,举个例子复习一下泛型通配符:

 1 package com.wang.practice;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 /**
 7  * 泛型————类型通配符
 8  * 类型通配符一般是使用?代替具体的类型"参数"。
 9  * 例如 List<?> 在逻辑上是List<String>,List<Integer> 等所有List<具体类型实参>的父类。
10  * @author Administrator
11  */
12 public class TestGenerics03 {
13 
14     /**
15      * @param args
16      */
17     public static void main(String[] args) {
18         List<String> name = new ArrayList<String>();
19         List<Integer> age = new ArrayList<Integer>();
20         List<Number> number = new ArrayList<Number>();
21 
22         name.add("icon");
23         age.add(18);
24         number.add(314);
25 
26         getData(name);
27         getData(age);
28         getData(number);
29 
30     }
31 
32     public static void getData(List<?> data) {
33         System.out.println("data :" + data.get(0));
34     }
35 
36 }
原文地址:https://www.cnblogs.com/wang--lei/p/7277222.html