簡體   English   中英

您可以將原始類型用於類或方法中的泛型參數嗎?

[英]Can you use primitive types for generic parameters in a class or method?

我正在寫一篇關於泛型的簡短文章,而我在Java中並沒有真正使用它們。 我想知道原始類型是否可以用作通用變量中的參數類型。 我無法使其與具有通用類型的通用參數一起編譯。

問題:對於泛型如何處理原始數據類型,我有些不確定。 有人可以舉例說明我如何必須聲明不同的方法,而不必在Integer中將強制類型轉換添加到int類型,以及是否可以在類聲明中使用原始Java數據類型。

   DDHGeneric<int,int,int,int> t = new DDHGeneric<int,int,int,int>();

有沒有辦法做到這一點?

以下聲明也不編譯。 我確實知道,從對泛型的了解來看,使用原始數據類型和用戶定義的類之間存在差異。

   DDHGeneric<int, int, int, int> temp2 = new  DDHGeneric<int, int, int, int>();

類:

public class DDHGeneric<T,K,Bigfoot,Pizza> {
    T a;
    K n;
    Bigfoot u;

    public DDHGeneric() {
    }

    private <rapper> void myMethod(rapper y) {
    int temp = y; <--Errors out on this line as will.
}

    public <Pizza> void myAddition(Pizza a, Pizza b) {
    }

    private <K> void me(K a, K b, K c) {
    }

    public static void main(String[] args) {
         DDHGeneric<int, Integer, Integer, Integer> temp = new  DDHGeneric<int, Integer, Integer, Integer>();
         temp.myAddition(5, 4);
         temp.a = "Test this string!" ;
    }
}

你不能。

Oracle 對此主題發表了一篇文章

報價:

創建對對象時,不能用基本類型替換類型參數K或V:

Pair<int, char> p = new Pair<>(8, 'a'); // compile-time error

您只能將非基本類型替換為類型參數K和V:

Pair<Integer, Character> p = new Pair<>(8, 'a');

沒有。

泛型不代表原始。 它們旨在表示對象(因為泛型類型都隱式擴展了Object )。

您可以使用所需的原始類的包裝器變體來實現相同的效果。

 DDHGeneric<Integer, Integer, Integer, Integer> t = new DDHGeneric<>();

這是“ 為什么使用泛型?”的簡短摘錄 ,可在Java Trail中找到:

簡而言之,泛型在定義類,接口和方法時使類型 (類和接口)成為參數。

泛型僅采用原始類,而不采用原始數據類型。

對於每種數據類型,使用其對應的類

DDHGeneric<int,int,int,int> t = new DDHGeneric<int,int,int,int>();

可以用作

DDHGeneric<Integer, Integer, Integer, Integer> t = new DDHGeneric<Integer, Integer, Integer, Integer>();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM