Java泛型系結型別擦除


Java編譯器用通用型別的型別引數替換其系結的有界型別引數。

範例

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

package com.yiibai.demo;

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

        integerBox.add(new Integer(130));
        doubleBox.add(new Double(134.99));

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

class Box<T extends Number> {
    private T t;

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

    public T get() {
        return t;
    }
}

執行上面程式碼,得到以下結果 -

Integer Value :130
Double Value :134.99