Java Generics 简明教程

Java Generics - Type Inference

类型推断表示 Java 编译器查看方法调用及其相应声明的能力,以检查和确定类型参数。推断算法检查参数的类型,如果可用,则返回已分配的类型。推断算法尝试找到一个特定类型,该类型可以满足所有类型参数。

Type inference represents the Java compiler’s ability to look at a method invocation and its corresponding declaration to check and determine the type argument(s). The inference algorithm checks the types of the arguments and, if available, assigned type is returned. Inference algorithms tries to find a specific type which can fullfill all type parameters.

如果未使用类型推断,编译器会生成未检查转换警告。

Compiler generates unchecked conversion warning in-case type inference is not used.

Syntax

Box<Integer> integerBox = new Box<>();

其中

Where

  1. Box − Box is a generic class.

  2. <> − The diamond operator denotes type inference.

Description

使用菱形运算符,编译器确定参数的类型。此运算符在 Java SE 7 版本中可用。

Using diamond operator, compiler determines the type of the parameter. This operator is avalilable from Java SE 7 version onwards.

Example

使用任意你选择的编辑器创建以下 Java 程序。

Create the following java program using any editor of your choice.

GenericsTester.java

package com.tutorialspoint;

public class GenericsTester {
   public static void main(String[] args) {
      //type inference
      Box<Integer> integerBox = new Box<>();
      //unchecked conversion warning
      Box<String> stringBox = new Box<String>();

      integerBox.add(new Integer(10));
      stringBox.add(new String("Hello World"));

      System.out.printf("Integer Value :%d\n", integerBox.get());
      System.out.printf("String Value :%s\n", stringBox.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

Integer Value :10
String Value :Hello World