什么是泛型?我們在工程代碼中一定看過T,K,V等等,這個就是泛型了,那我們看看官網是怎么說的這個@泛型(Generic)
When you take an element out of a Collection , you must cast it to the type of element that is stored in the collection. Besides being inconvenient, this is unsafe. The compiler does not check that your cast is the same as the collection's type, so the cast can fail at run time.
Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection.官方這話是什么意思呢:當你從集合中取出元素時,必須將其強制轉換為存盤在集合中的元素型別,除了不方便,這是不安全的,編譯器不會檢查強制轉換是否與集合的型別相同,因此強制轉換可能會在運行時失敗,
泛型提供了一種將集合的型別傳遞給編譯器的方法,以便可以對其進行檢查,一旦編譯器知道集合的元素型別,編譯器就可以檢查您是否一致地使用了集合,并且可以對從集合中取出的值插入正確的強制轉換,官方這段晦澀的語言什么意思呢?總之就是一句話:泛型程式設計(Generic programming)意味著撰寫的代碼可以被很多不同型別的物件所重用,
Java泛型(Generic)是J2SE1.5中引入的一個新特性,其本質是引數化型別,也就是說所操作的資料型別被指定為一個引數(type parameter)這種引數型別可以用在類、介面和方法的創建中,分別稱為泛型類、泛型介面、泛型方法,
了解泛型概念之后的學習的目標是什么呢?
一、了解泛型的規則與型別擦除
二、了解型別和限制兩種泛型的通配符
三、了解在API設計時使用泛型的方式(自定義泛型類、泛型介面、泛型方法)
四、掌握泛型的使用及原理,
五、掌握泛型在中間件或者開源框架里的應用
下面我們對這幾個問題一一探討
泛型的規則
JDK5.0之前是沒有泛型這個概念的,那么當時是怎么寫代碼的
import java.io.File;
import java.util.ArrayList;
/**
* @author mac
* @date 2020/10/31-11:05
*/
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add(1);
arrayList.add("a");
// 這里沒有錯誤檢查,可以向陣列串列中添加任何類的物件
arrayList.add(new File("/"));
// 對于這個呼叫,如果將get的結果強制型別轉換為String型別,就會產生一個錯誤
// Exception in thread "main" java.lang.ClassCastException: java.io.File cannot be cast to java.lang.String
String file = (String) arrayList.get(2);
System.out.println(file);
}
在 JDK5.0以前,如果一個方法回傳值是 Object,一個集合里裝的是 Object,那么獲取回傳值或元素只能強轉,如果有型別轉換錯誤,在編譯器無法覺察,這就大大加大程式的錯誤幾率!
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("a");
String s = (String) arrayList.get(0);
// 6、7行代碼編譯不通過,不會導致運行后才發生錯誤
arrayList.add(1);
arrayList.add(new File("/"));
String file = (String) arrayList.get(2);
}
從泛型的使用可以看出,泛型是一種型別約束,簡而言之,泛型在定義類,介面和方法時使型別(類和介面)成為引數,與方法宣告中使用的更熟悉的形式引數非常相似,型別引數為您提供了一種使用不同輸入重復使用相同代碼的方法,區別在于形式引數的輸入是值,而型別引數的輸入是型別,
JDK是在編譯期對型別進行檢查,提供了編譯時型別的安全性,它為集合框架增加了編譯時型別的安全性,并消除了繁重的型別轉換作業,
public class Person {
int gender;
}
public class Driver extends Person {
String name;
int skilllevel;
}
public static void main(String[] ars) {
List<Person> ls = new Arraylist<>();
//這里會不會編譯報錯?
List<Driver> list = ls;
}
然而泛型的應用也不是沒有坑,比如上述代碼,可以看出編譯報錯,這是不允許子型別化的泛型規則——假設允許,那么是不是可以改成以下的情況,在 JDK 里所有的類都是 Object 的子類,如果允許子類
型化,那么ls里不就可以存放任意型別的元素了嗎,這就和泛型的型別約束完全相悖,所以 JDK 在泛型的校驗上有很嚴格的約束,
為了防止子型別化混亂,泛型有了通配符的概念
泛型中的通配符
無界通配符
在上述的泛型示例中,我們都是指定了特定的型別,至少也是 Object,假設有一種場景,你不知道這個型別是啥,它可以是 Object,也可以是 Person 那咋辦?這種場景就需要用到通配符,如
下所示,通常采用一個?來表示,
public void addAll(Collection<?> col){
...
}
上界通配符
基于上述的場景,加入我想限制這個型別為 Person 的子類,只要是 Person 的子類就都可以,如果泛型寫成<Person> 那么只能強轉如下所示,那么就失去了泛型的意義,又回到了最初的起點,這時候怎么辦?
List<Person> list = new ArrayList<>();
list.add(new Driver());
Person person = list.get(0);
Driver driver = (Driver) person; // 針對這種情況于是有了有界通配符的推出,

// 在泛型中指定上邊界的叫上界通配符<? extends XXX>
public void count(Collection<? extends Person> persons) {
}
public void count2(Collection<Person> persons) {
}
public void testCount() {
List<Driver> drivers = new ArrayList<>();
// 符合上界通配符規則,編譯不報錯
count(drivers);
// 違反子型別化原則,編譯報錯
count2(drivers);
// 符合下界通配符原則,編譯不報錯
List<Person> persons = new ArrayList<>();
}
下界通配符
原理同上界通配符, 下界通配符將未知型別限制為特定型別或該型別的超型別,下限通配符使用通配符(' ? ')表示,后跟 super 關鍵字,后跟下限:<?super A>,

public void count3(Collection<? super Driver> drivers) {
}
public void testCount() {
//符合下界通配符原則,編譯不報錯
List<Person> persons = new ArrayList<>();
count3(persons);
}
通用方法與型別推斷
通用方法
通用方法是指方法引數的型別是泛型,static 和非 static 的方法都可以使用,還有就是構造方法也可以使用,我們看具體的使用
/**
* @author mac
* @date 2020/10/31-12:24
* 定義一個bean類
*/
public class Pair<K, V> {
private K key; private V value;
public Pair(K key, V value) {
this.key = key; this.value = value;
}
public void setKey(K key) { this.key = key; }
public void setValue(V value) { this.value = value; }
public K getKey() { return key; }
public V getValue() { return value; }
}
public class Util {
// <K, V>通用方法入參型別
public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) {
return p1.getKey().equals(p2.getKey()) &&
p1.getValue().equals(p2.getValue()); // 使用Object中equals判斷是否相等
}
}
public static void main(String[] args) {
Pair<Integer, String> p1 = new Pair<>(1, "apple");
Pair<Integer, String> p2 = new Pair<>(2, "pear");
// JDK8之后可以這么寫boolean same = Util.compare(p1, p2);
boolean same = Util.<Integer, String>compare(p1, p2);
System.out.println(same); // false
}
型別推斷
型別推斷是Java編譯器查看每個方法呼叫和相應宣告以確定使呼叫適用的型別引數的能力,推理演算法確定引數的型別,以及確定結果是否已分配或回傳的型別(如果有),最后,推理演算法嘗試找到與所有引數一起使用的最具體的型別,
/**
* @author macfmc
* @date 2020/10/31-12:39
*/
public class Box<U> {
U u;
public U get() { return u; }
public void set(U u) { this.u = u; }
}
public class BoxDemo {
public static <U> void addBox(U u, List<Box<U>> boxes) {
Box<U> box = new Box<U>();
box.set(u);
boxes.add(box);
}
public static <U> void outputBoxes(List<Box<U>> boxes) {
int counter = 0;
for (Box<U> box : boxes) {
U boxContents = box.get();
System.out.println("Box #" + counter + " contains [" + boxContents.toString() + "]");
counter++;
}
}
public static void main(String[] args) {
ArrayList<Box<Integer>> listOfIntegerBoxes = new ArrayList<>();
// JDK8可以使用 BoxDemo.addBox(Integer.valueOf(10), listOfIntegerBoxes);
BoxDemo.<Integer>addBox(Integer.valueOf(10), listOfIntegerBoxes);
BoxDemo.addBox(Integer.valueOf(20), listOfIntegerBoxes);
BoxDemo.addBox(Integer.valueOf(30), listOfIntegerBoxes);
BoxDemo.outputBoxes(listOfIntegerBoxes);
}
}
// 結果
// Box #0 contains [10]
// Box #1 contains [20]
// Box #2 contains [30]
那么泛型的概念原理和使用都了解了,泛型在JVM中是如何去決議的呢?
泛型擦除
我們看下面兩段代碼
public class Node {
private Object obj;
public Object get() { return obj; }
public void set(Object obj) { this.obj = obj; }
public static void main(String[] argv) {
Student stu = new Student();
Node node = new Node();
node.set(stu);
Student stu2 = (Student) node.get();
}
}
public class Node<T> {
private T obj;
public T get() { return obj; }
public void set(T obj) { this.obj = obj; }
public static void main(String[] argv) {
Student stu = new Student();
Node<Student> node = new Node<>();
node.set(stu);
Student stu2 = node.get();
}
}
我們將其分別編譯后查看.class位元組碼檔案
public Node();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>": ()V
4: return
public java.lang.Object get();
Code:
0: aload_0
1: getfield #2 // Field obj:Ljava/lang/Object;
4: areturn
public void set(java.lang.Object);
Code:
0: aload_0
1: aload_1
2: putfield #2 // Field obj:Ljava/lang/Object;
5: return
public Node();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>": ()V
4: return
public java.lang.Object get();
Code:
0: aload_0
1: getfield #2 // Field obj:Ljava/lang/Object;
4: areturn
public void set(java.lang.Object);
Code:
0: aload_0
1: aload_1
2: putfield #2 // Field obj:Ljava/lang/Object;
5: return
可以看到泛型就是在使用泛型代碼的時候,將型別資訊傳遞給具體的泛型代碼,而經過編譯后,生成的 .class 檔案和原始的代碼一模一樣,就好像傳遞過來的型別資訊又被擦除了一樣,
型別擦除主要包括:一、通用型別的檫除:在型別擦除程序中,Java 編譯器將擦除所有型別引數,如果型別引數是有界的,則將每個引數替換為其第一個邊界;如果型別引數是無界的,則將其替換為 Object,二、通用方法的擦除:java 編譯器還會檫除通用方法引數中的型別引數
型別檫除的問題
橋接方法
型別檫除在有一些情況下會產生意想不到的問題,為了解決這個問題,java 編譯器采用橋接方法的方式,先看個官方案例
// 泛型擦除前
public class Node<T> {
public T data;
public Node(T data) { this.data = data; }
public void setData(T data) { this.data = data; }
}
public class MyNode extends Node<Integer> {
public MyNode(Integer data) { super(data); }
public void setData(Integer data) { super.setData(data); }
}
// 泛型檫除后
public class Node {
public Object data;
public Node(Object data) { this.data = data; }
public void setData(Object data) { this.data = data; }
}
public class MyNode extends Node {
public MyNode(Integer data) { super(data); }
public void setData(Integer data) { super.setData(data); }
}
// 但是編譯器會產生橋接方法
public class MyNode extends Node {
public MyNode(Object data) { super(data); }
// Bridge method generated by the compiler
// 編譯器產生的橋接方法
public void setData(Object data) { setData((Integer) data); }
public void setData(Integer data) { super.setData(data); }
}
堆污染
堆污染在編譯時并不會報錯,只會在編譯時提示有可能導致堆污染的警告.,在運行時,如果發生了堆污染,那么就會拋出型別轉換例外,Heap pollution(堆污染),,指的是當把一個不帶泛型的物件賦值給一個帶泛型的變數時,就有可能發生堆污染,
public static void main(String[] args) {
List lists = new ArrayList<Integer>();
lists.add(1);
List<String> list = lists;
// java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
String str = list.get(0);
System.out.println(str);
}
型別的限制
Java泛型轉換的事實:
虛擬機中沒有泛型,只有普通的類和方法,
所有的型別引數都用它們的限定型別替換,
橋接方法被合成來保持多型,
為保持型別安全性,必要時插入強制型別轉換,
jdk定義了7種泛型的使用限制:
1、不能用簡單型別來實體化泛型實體
2、不能直接創建型別引數實體
3、不能宣告靜態屬性為泛型的型別引數
4、不能對引數化型別使用cast或instanceof
5、不能創建陣列泛型
6、不能create、catch、throw引數化型別物件
7、多載的方法里不能有兩個相同的原始型別的方法
1、不能用簡單型別來實體化泛型實體
class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) { this.key = key; this.value = value; }
public static void main(String[] args) {
// 編譯時會報錯,因為 int、char 屬于基礎型別,不能用于實體化泛型物件
Pair<int, char> p = new Pair(8, 'a');
// 編譯不會報錯
Pair<Integer, String> p2 = new Pair<>(8, "a");
}
}
2、不能直接創建型別引數實體
public static <E> void append(List<E> list) {
E elem = new E(); // compile-time error 編譯報錯
list.add(elem);
}
//作為解決辦法,可以通過反射來創建
public static <E> void append(List<E> list, Class<E> cls) throws Exception {
E elem = cls.newInstance(); // OK
list.add(elem);
}
3、不能宣告靜態屬性為泛型的型別引數
/**
* 類的靜態欄位是該類所有非靜態物件所共享的,如果可以,那么在有多種型別的情況下,os到底應該是哪種型別呢?
* 下面這種情況,os到底應該是Smartphone還是Pager還是TablePC呢
* MobileDevice<Smartphone> phone = new MobileDevice<>();
* MobileDevice<Pager> pager = new MobileDevice<>();
* MobileDevice<TabletPC> pc = new MobileDevice<>();
*/
public class MobileDevice<T> {
//非法
private static T os;
}
4、不能對引數化型別使用cast或instanceof
public static <E> void rtti(List<E> list) {
// 編譯期會提示例外——因為 java 編譯器在編譯器會做型別檫除,于是在運行期就無法校驗引數的型別
if (list instanceof ArrayList<Integer>) { }
}
// 解決方法可以通過無界通配符來進行引數化
public static void rtti(List<?> list) {
// 編譯不會報錯
if (list instanceof ArrayList<?>) { }
}
5、不能創建陣列泛型
// 編譯器報錯
List<Integer>[] arrayOfLists = new List<Integer>[2];
// 用一個通用串列嘗試同樣的事情,會出現一個問題
Object[] strings = new String[2];
strings[0] = "hi"; // OK
strings[1] = 100; // An ArrayStoreException is thrown.
Object[] stringLists = new List<String>[]; // compiler error, but pretend it's allowed 缺少陣列維
stringLists[0] = new ArrayList<String>(); // OK
// java.lang.ArrayStoreException: java.util.ArrayList but the runtime can't detect it.
stringLists[1] = new ArrayList<Integer>();
6、不能create、catch、throw引數化型別物件
// 泛型類不能直接或間接的擴展 Throwable 類,以下情況會報編譯錯
// Extends Throwable indirectly
class MathException<T> extends Exception { } // compile-time error
// Extends Throwable directly
class QueueFullException<T> extends Throwable { } // compile-time error
// 捕捉泛型例外也是不允許的
public static <T extends Exception, J> void execute(List<J> jobs) {
try {
for (J job : jobs) { }
} catch (T e) { // compile-time error
}
}
// 但是可以在字句中使用型別引數
class Parser<T extends Exception> {
public void parse(File file) throws T { }
}
7、多載的方法里不能有兩個相同的原始型別的方法
// 因為型別檫除后,兩個方法將具有相同的簽名,多載將共享相同的類檔案表示形式,并且將生成編譯時錯誤,
public class Example {
public void print(Set<String> strSet) { }
public void print(Set<Integer> intSet) { }
}
總結:
代碼中泛型的演變程序和泛型的使用及為什么使用是基礎算是會用,泛型的三種通配符的使用及使用規則和通用方法的使用及型別推斷是進階算是了解,型別擦除及型別擦除的問題和型別的使用限制是補充算是熟悉,能了解泛型在JDK原始碼中的常用API的設計方式算是精通,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/200659.html
標籤:其他
上一篇:世間最沒有道理的是喜歡?也對,喜歡這種東西講道理做什么 (小康小白)
下一篇:C++學習筆記第一天
