標籤:集合泛型 類泛型 方法泛型 generic
泛型 Generic Types
import java.util.ArrayList;import java.util.List;/* * 泛型 Generic Types * 集合泛型 * 類泛型 * 方法泛型 */public class Test01 { public static void main(String[] args) { // 1.集合泛型,保證集合中元素的型別安全 List<Integer> nums = new ArrayList<Integer>(); nums.add(25); // nums.add("tom"); //只能添加整型數值 // 2.類泛型 Student stu1 = new Student("tom"); stu1.obj = 25; // Object無法保證類型的安全 stu1.show(); //建立泛型類的對象時需要指定具體的資料類型,保證資料安全 Student2<String> stu2=new Student2<String>("jack"); //stu2.t=38; stu2.show(); // 3.方法泛型 print("tom"); print(20); print(13.5); } public static <T> void print(T t){ System.out.println(t.getClass()); }}/* * 普通的類 */class Student { Object obj; public Student(Object obj) { this.obj = obj; } public void show() { System.out.println(obj); }}/* * 泛型類 */class Student2<T> { T t; public Student2(T t) { this.t = t; } public void show(){ System.out.println(t); }}
JAVA學習筆記(五十六)- 泛型 Generic Types