Java泛型中的原始型別是什麼?


泛型是Java中一個概念,您可以使用它使類、介面和方法接受所有(引用)型別作為引數。換句話說,它是一個允許使用者動態選擇方法、類建構函式接受的引用型別的概念。透過將類定義為泛型,您使其型別安全,即它可以作用於任何資料型別。

要定義一個泛型類,您需要在類名後的尖括號“<>”中指定您正在使用的型別引數,您可以將其視為例項變數的資料型別並繼續編寫程式碼。

示例 - 泛型類

class Person<T>{
   T age;
   Person(T age){
      this.age = age;
   }
   public void display() {
      System.out.println("Value of age: "+this.age);
   }
}

用法 - 在例項化泛型類時,您需要在類後的尖括號內指定物件名稱。因此,動態選擇型別引數的型別並傳遞所需的物體作為引數。

public class GenericClassExample {
   public static void main(String args[]) {
   Person<Float> std1 = new Person<Float>(25.5f);
      std1.display();
      Person<String> std2 = new Person<String>("25");
      std2.display();
      Person<Integer> std3 = new Person<Integer>(25);
      std3.display();
   }
}

原始型別

在建立泛型類或介面的物件時,如果您沒有提及型別引數,則它們被稱為原始型別。

例如,如果您觀察上面的示例,在例項化Person類時,您需要在尖括號中為型別引數(類的型別)指定型別。

如果您避免在尖括號內指定任何型別引數並建立泛型類或介面的物件,則它們被稱為原始型別。

public class GenericClassExample {
   public static void main(String args[]) {
      Person per = new Person("1254");
      std1.display();
   }
}

警告

這些將在沒有錯誤的情況下編譯,但會生成如下所示的警告。

Note: GenericClassExample.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details

以下是關於原始型別的一些值得注意的要點:

  • 您可以將引數化(泛型)型別分配給其原始型別。
public class GenericClassExample {
   public static void main(String args[]) {
     Person per = new Person(new Object());
       per = new Person<String>("25");
      per.display();
    }
}

輸出

Value of age: 25
  • 如果您將原始型別分配給引數化型別,則會生成警告。
public class GenericClassExample {
   public static void main(String args[]) {
      Person<String> obj = new Person<String>("");
      obj = new Person(new Object());
      obj.display();
   }
}

警告

Note: GenericClassExample.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
  • 如果您的泛型類包含一個泛型方法,並且您嘗試使用原始型別呼叫它,則會在編譯時生成警告。

public class GenericClassExample {
   public static void main(String args[]) {
      Student std = new Student("Raju");
      System.out.println(std.getValue());
   }
}

警告

Note: GenericClassExample.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

更新於:2019年9月9日

477 次檢視

開啟您的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.