Java泛型的總結
泛型可以用於介面、類、方法上。還有泛型通配符這個概念
泛型的好處:可以在編譯時檢查
1.用於方法中,指定該方法中的形參的類型。
語法:修飾符 <代表泛型的變數> 返回值類型 方法名(參數){ }
注意:方法上定義了是什麼 泛型變數 ,後面就只能用什麼 泛型變數。
package com.itheima.hw;
import java.util.Arrays;
/**
* @author Pzi
* @create 2022-09-27 9:57
*/
public class GenericArray {
// 泛型方法,交換數組中兩個索引位置的值
public static <T> void swap(T[] arr, int index1, int index2) {
T temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+"\t");
}
}
public static void main(String[] args) {
int[] arr = new int[]{1,2,3,4,5,6};
Integer newNums[] = Arrays.stream(arr).boxed().toArray(Integer[]::new);
swap(newNums, 0,1);
}
}
2.用於類上
修飾符 class 類名<代表泛型的變數> { }
3.用於介面上
修飾符 interface介面名<代表泛型的變數> { }
- 如果某個類要實現某個泛型介面,但是該實現類也不確定類型,如下定義
public class MyImpl3<E> implements MyGenericInterface<E> {
@Override
public void add(E e) {
}
@Override
public E getE() {
return null;
}
}
4.泛型通配符
可以用來指定傳入類型的上限和下限
可以用來表示位置的類型,比如說一個方法中形參的類型
如:
public static void getElement(Collection<?> coll){}
類型名稱 <? extends 類 > 對象名稱
表示只能傳入該類或者其子類
類型名稱 <? super 類 > 對象名稱
表示只能傳入該類或其父類