Java泛型不能使用原始型別


使用泛型,原始型別不能作為型別引數傳遞。在下面給出的例子中,如果將int原始型別傳遞給Box類,那麼編譯器會報錯。為了避免這種情況,我們需要傳遞Integer物件(而不是int原始型別)。

範例

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

package com.yiibai.dem4;

public class NoPrimitiveTypes {

    public static void main(String[] args) {

        Box<Integer> integerBox = new Box<Integer>();

        // compiler errror
        // ReferenceType
        // - Syntax error, insert "Dimensions" to complete
        // ReferenceType
        // Box<int> stringBox = new Box<int>();

        integerBox.add(new Integer(1990));
        printBox(integerBox);
    }

    private static void printBox(Box box) {
        System.out.println("Value: " + box.get());
    }
}

class Box<T> {
    private T t;

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

    public T get() {
        return t;
    }
}

執行上面程式碼,得到輸出結果如下 -

Value: 1990