Java Generics 简明教程

Java Generics - No Primitive Types

使用泛型,不能将基本类型作为类型参数传递。在下面给出的示例中,如果我们将 int 基本类型传递给框类,则编译器会抱怨。为了缓解这种情况,我们需要传递 Integer 对象,而不是 int 基本类型。

Using generics, primitive types can not be passed as type parameters. In the example given below, if we pass int primitive type to box class, then compiler will complain. To mitigate the same, we need to pass the Integer object instead of int primitive type.

Example

package com.tutorialspoint;

public class GenericsTester {
   public static void main(String[] args) {
      Box<Integer> integerBox = new Box<Integer>();

      //compiler errror
      //ReferenceType
      //- Syntax error, insert "Dimensions" to complete
      ReferenceType
      //Box<int> stringBox = new Box<int>();

      integerBox.add(new Integer(10));
      printBox(integerBox);
   }

   private static void printBox(Box box) {
      System.out.println("Value: " + box.get());
   }
}

class Box<T> {
   private T t;

   public void add(T t) {
      this.t = t;
   }

   public T get() {
      return t;
   }
}

这会产生以下结果 −

This will produce the following result −

Output

Value: 10