CodesJava

Easy learning with example program codes

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


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2019 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki