在 Java 中实例化参数化类型(泛型)时传递原始值?

java 8object oriented programmingprogramming

泛型是 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

相关文章