English 中文(简体)
Java Generics - Type inference
  • 时间:2024-12-22

Java Generics - Type Inference


Previous Page Next Page  

Type inference represents the Java compiler s abipty 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

    Box − Box is a generic class.

    <> − The diamond operator denotes type inference.

Description

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

Example

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

GenericsTester.java

package com.tutorialspoint;

pubpc class GenericsTester {
   pubpc 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
", integerBox.get());
      System.out.printf("String Value :%s
", stringBox.get());
   }
}

class Box<T> {
   private T t;

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

   pubpc T get() {
      return t;
   }   
}

This will produce the following result.

Output

Integer Value :10
String Value :Hello World
Advertisements