Java泛型無界型別擦除


如果使用無界型別引數,則Java編譯器將使用Object替換型別引數。

範例

建立一個名稱為:UnboundedTypesErasure.java 檔案,並編寫以下程式碼 -

package com.yiibai.demo2;

public class UnboundedTypesErasure {
    public static void main(String[] args) {
        Box<Integer> integerBox = new Box<Integer>();
        Box<String> stringBox = new Box<String>();

        integerBox.add(new Integer(1000));
        stringBox.add(new String("Hello World"));

        System.out.printf("Integer Value :%d\n", integerBox.get());
        System.out.printf("String Value :%s\n", stringBox.get());
    }
}

class Box<T> {
    private T t;

    public void add(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }
}

在本範例中,java編譯器將用Object類替換T,而在型別擦除之後,編譯器會為以下程式碼生成位元組碼。

package com.yiibai.demo2;

public class UnboundedTypesErasure {
    public static void main(String[] args) {
        Box integerBox = new Box();
        Box stringBox = new Box();

        integerBox.add(new Integer(1000));
        stringBox.add(new String("Hello World"));

        System.out.printf("Integer Value :%d\n", integerBox.get());
        System.out.printf("String Value :%s\n", stringBox.get());
    }
}

class Box {
    private Object t;

    public void add(Object t) {
        this.t = t;
    }

    public Object get() {
        return t;
    }
}

在這兩種情況下,執行輸出結果是相同的 -

Integer Value :1000
String Value :Hello World