在 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 class GenericsExample {
   public static void main(String args[]) {
      Student<Float> std1 = new Student<Float>(25.5f);
      Student<String> std2 = new Student<String>("25");
      Student<int> std3 = new Student<int>(25);
   }
}

編譯時錯誤

GenericsExample.java:11: error: unexpected type
      Student<int> std3 = new Student<int>(25);
          ^
   required: reference
   found: int
GenericsExample.java:11: error: unexpected type
      Student<int> std3 = new Student<int>(25);
                                    ^
   required: reference
   found: int
2 errors

示例

 即時演示

public class GenericMethod {
   <T>void sampleMethod(T[] array) {
      for(int i=0; i<array.length; i++) {
         System.out.println(array[i]);
      }
   }
   public static void main(String args[]) {
      GenericMethod obj = new GenericMethod();
      Integer intArray[] = {45, 26, 89, 96};
      obj.sampleMethod(intArray);
      String stringArray[] = {"Krishna", "Raju", "Seema", "Geeta"};
      obj.sampleMethod(stringArray);
      char charArray[] = {'a', 's', 'w', 't'};
      obj.sampleMethod(charArray);
   }
}

輸出

GenericMethod.java:16: error: method sampleMethod in class GenericMethod cannot be applied to given types;
      obj.sampleMethod(charArray);
      ^
   required: T[]
   found: char[]
   reason: inference variable T has incompatible bounds
      equality constraints: char
      upper bounds: Object
   where T is a type-variable:
      T extends Object declared in method <T>sampleMethod(T[])
1 error

更新於: 2019 年 9 月 9 日

473 次瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告