Java泛型時JDK1.5中引入的一個新特性,其本質化是參數化類型,把類型作為參數傳遞
常見形式有泛型類 \ 泛型接口 \ 泛型方法
語法 : <T,...> T稱為類型占位符,表示一種引用類型
2 防止類型轉換異常, 提高代碼安全性
泛型類
/**
* 泛型類
* 語法:類名<T>
* T是類型占位符,表示一種應用類型,如果寫多個,用逗號隔開
*/
public class MyGeneric<T> {
//使用泛型T
//創建變量
T t;
//作為方法的參數
public void show(T t){
//不能用泛型直接new對象
System.out.println(t);
}
//使用泛型作為方法返回值
public T getT(){
return t;
}
}
public class TestGeneric {
public static void main(String[] args) {
//使用泛型類創建對象
//注意:1.泛型只能是引用類型 2.不同的泛型類型對象之間不能相互賦值
MyGeneric<String> myGeneric = new MyGeneric<String>();
myGeneric.t = "hello";
myGeneric.show("大家好!加油!");
String string = myGeneric.getT();
MyGeneric<Integer> myGeneric2 = new MyGeneric<Integer>();
myGeneric2.t = 100;
myGeneric2.show(200);
Integer integer =myGeneric2.getT();
}
}
泛型接口
/**
* 泛型接口
* 語法:接口名<T>
* 注意:不能使用泛型創建靜態常量
*/
public interface MyInterface<T> {
String name = "張三";
T sever(T t);
}
使用方法一
繼承的時候直接確定類型
public class MyInterfaceImpl implements MyInterface<String>{
使用方法二
繼承的時候不確定類型
public class MyInterfaceImp2<T> implements MyInterface<T>{
泛型方法
/**
* 泛型方法
* 語法: <T> 返回值類型
*/
public class MyGenericMethod {
//泛型方法
public <T> T show(T t){
System.out.println("泛型方法: "+t);
return t;
}
}
public class TestGeneric {
public static void main(String[] args) {
//泛型方法調用
MyGenericMethod myGenericMethod = new MyGenericMethod();
myGenericMethod.show("中國");//這里的泛型根據所放入的值來改變
myGenericMethod.show(1000);//這里的泛型根據所放入的值來改變
myGenericMethod.show(314);//這里的泛型根據所放入的值來改變
}
}
泛型集合
概念: 參數化類型、類型安全的集合,強制集合元素的類型必須一致
特點:
-
編譯時即可檢查,而非運行時拋出異常
-
訪問時,不必類型轉換(拆箱)
-
不同泛型之間引用不能相互賦值,泛型不存在多態
public class Demo1 {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
//指定了泛型 此時此刻就不能添加除字符串以外的類型
arrayList.add("xxx");
arrayList.add("yyy");
for (String s : arrayList) {
System.out.println(s);
}
ArrayList<Student> arrayList2 = new ArrayList<>();
Student s1 = new Student("張三",20);
Student s2 = new Student("李四",18);
Student s3 = new Student("王二",22);
arrayList2.add(s1);
arrayList2.add(s2);
arrayList2.add(s3);
Iterator<Student> it = arrayList2.iterator();
while (it.hasNext()){
Student s = it.next();
System.out.println(s.toString());
}
}
}
附:Student類
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}