- Java Generics Tutorial
- Java Generics - Home
- Java Generics - Overview
- Java Generics - Environment Setup
- Examples - Generic Classes
- Java Generics - Generic Classes
- Type Parameter Naming Conventions
- Java Generics - Type inference
- Java Generics - Generic Methods
- Java Generics - Multiple Type
- Java Generics - Parameterized Types
- Java Generics - Raw Types
- Examples - Bounded Type
- Bounded Type Parameters
- Java Generics - Multiple Bounds
- Examples - Collections
- Java Generics - Generic List
- Java Generics - Generic Set
- Java Generics - Generic Map
- Examples - Wild Cards
- Upper Bounded Wildcards
- Generics - Unbounded Wildcards
- Lower Bounded Wildcards
- Generics - Guidelines for Wildcards
- Type Erasure
- Java Generics - Types Erasure
- Java Generics - Bound Types Erasure
- Unbounded Types Erasure
- Java Generics - Methods Erasure
- Restrictions on Generics
- Java Generics - No Primitive Types
- Java Generics - No Instance
- Java Generics - No Static field
- Java Generics - No Cast
- Java Generics - No instanceOf
- Java Generics - No Array
- Java Generics - No Exception
- Java Generics - No Overload
- Java Generics Useful Resources
- Java Generics - Quick Guide
- Java Generics - Useful Resources
- Java Generics - Discussion
Java Generics - Type Inference
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
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 avalilable from Java SE 7 version onwards.
Example
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
To Continue Learning Please Login
Login with Google