Java 7 Type Inference

Java 7 introduced a new feature Type Interface which provides ability to compiler to infer the type of generic instance. We can replace the type arguments with an empty set of type parameters (<>) diamond. Before Java 7 following approach was used:

List list = new List();  

We can use following approach with Java 7:

List list = new List<>(); 

We just used diamond here and type argument is there.

Example

package com.w3schools;

import java.util.ArrayList;
import java.util.List;

public class TestExample {
	public static void main(String args[]){
		 //Prior to Java 7    
        List list1 = new ArrayList();  
        list1.add(10);  
        for (Integer element : list1) {  
            System.out.println(element);  
        }  
        //In Java 7, Only diamond is used 
        List list2 = new ArrayList<>();   
        list2.add(10);  
        for (Integer element : list2) {  
            System.out.println(element);  
        }  
	}  
}

Output

10
10
Please follow and like us:
Content Protection by DMCA.com