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<Integer> list = new List<Integer>();

We can use following approach with Java 7:

List<Integer> list = new List<>();

We just used diamond here and type argument is there.

Example

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

Output

10
10
Content Protection by DMCA.com
Please Share