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<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.

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.w3spoint;
 
import java.util.ArrayList;
import java.util.List;
 
public class TestExample {
	public static void displayList(List<Integer>list){  
         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<Integer> list1 = new ArrayList<Integer>();  
        list1.add(41);  
        displayList(list1);  
        // Java 7, We can left it blank, compiler can infer type
        List<Integer> list2 = new ArrayList<>();   
        list2.add(32);  
        displayList(list2);  
        //In Java 8, Compiler infers type of ArrayList
        displayList(new ArrayList<>());    
	}  
}

Example

41
32
Empty list
Content Protection by DMCA.com
Please Share