Pages

Wednesday, October 18, 2017

Java Type Inference in Generics

Type Inference in Generic

In Java 7, Type Inference is introduced in generics declaration which is used to reduce the coding as well to minimize the compile errors.

Made compiler smart enough to infer the type of generic instance. This is done by using "<>" operator and it is called as Diamond Operator. Not required to mention the type in between diamond operator and can be replaced declaring the type as left blank.

Java Type Inference in Generics

Generics declaration in Java 6 Example:


List<String> list = new ArrayList<String>();


public class GenericsInJava6 {
    // Java - W3schools
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("Type Inference");
    }
}

Generics declaration in Java 7 Example:


public class GenericsInJava7 {
    // Java - W3schools
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Java 7");
    }
}
In Java 7, Compiler has capable to check the type at compile time.

Type Inference Example:


package com.adeepdrive.arraylist;

public class GenericsInference {
    // Java - W3schools
    public static void main(String[] args) {

        // Generic String type
        Animal<String> animalName = new Animal<>();
        animalName.set("Horse");
        System.out.println("animalName :: " + animalName.get());
   
        // Generic Float type        
        Animal<Float> animalHeight = new Animal<>();
        animalHeight.set(7.5f);
        System.out.println("animalHeight :: " + animalHeight.get());
    }
}

class Animal<T> {
    private T t;

    public void set(T t) {
        this.t = t;
    }

    public T get() {
        return this.t;
    }
}

Output:


animalName :: Horse
animalHeight :: 7.5

Explanation:


Here we have a class Animal which can accept any type. Type can be String, Integer, Book, Trade, etc.

Create two Animal instances with type String, Float. animalName, animalHeight holds different type of values.

Generics in Java

No comments:

Post a Comment

Please do not add any spam links in the comments section.