您可以在 Java 中建立一個泛型型別陣列嗎?
泛型是 Java 中的一個概念,您可以使用它來使類、介面和方法接受所有(引用)型別作為引數。換句話說,它使使用者可以動態選擇方法或類建構函式接受的引用型別。透過將類定義為泛型,您可以使其型別安全,即它可以作用於任何資料型別。
示例
class Student<T>{
T age;
Student(T age){
this.age = age;
}
public void display() {
System.out.println("Value of age: "+this.age);
}
}
public class GenericsExample {
public static void main(String args[]) {
Student<Float> std1 = new Student<Float>(25.5f);
std1.display();
Student<String> std2 = new Student<String>("25");
std2.display();
Student<Integer> std3 = new Student<Integer>(25);
std3.display();
}
}輸出
Value of age: 25.5 Value of age: 25 Value of age: 25
泛型型別的陣列
不,我們無法建立泛型型別物件的陣列,如果您嘗試這樣做,將生成編譯時錯誤。
示例
class Student<T>{
T age;
Student(T age){
this.age = age;
}
public void display() {
System.out.println("Value of age: "+this.age);
}
}
public class GenericsExample {
public static void main(String args[]) {
Student<Float>[] std1 = new Student<Float>[5];
}
}編譯時錯誤
GenericsExample.java:12: error: generic array creation Student<Float>[] std1 = new Student<Float>[5]; ^ 1 error
Advertisement
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP