Java 8 Type Inference improvements

Type Interface feature was introduced in Java 7 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.

Java 8 Type interface improvement:

displayList(new ArrayList<>());

In java 8 we can call specialized method without explicitly mentioning of type of arguments.

Example

package com.w3schools;

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

public class TestExample {
	public static void displayList(Listlist){  
         if(!list.isEmpty()){  
            list.forEach(System.out::println);  
         }else{
        	System.out.println("Empty list");  
         }
        }  
	public static void main(String args[]){
		//Prior to Java 7  
        List list1 = new ArrayList();  
        list1.add(41);  
        displayList(list1);  
        // Java 7, We can left it blank, compiler can infer type
        List list2 = new ArrayList<>();   
        list2.add(32);  
        displayList(list2);  
        //In Java 8, Compiler infers type of ArrayList
        displayList(new ArrayList<>());    
	}  
}

Example

41
32
Empty list
Please follow and like us:
Content Protection by DMCA.com