Skip to content

Latest commit

 

History

History
59 lines (46 loc) · 1.17 KB

File metadata and controls

59 lines (46 loc) · 1.17 KB

Type Inference

A Java Compiler's ability to simplify Generics usage.

public class Box<T> {
    private T type;

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

    public T get() {
        return type;
    }

    // T is a type parameter
}
public class Util {

    public static <T> void displayToString(T type) {
        System.out.println(type.toString());
    }

}
  • Type Inference - Methods

    Util.<Animal>displayToString(favoriteAnimal);

    Instead of adding the <> we can do the following:

    Util.displayToString(favoriteAnimal);

    They are both correct but the second one is easier to use.

  • Type Inference - Instantiation of Generic Classes

    Box<Integer> favoriteNumber = new Box<Integer>();

    Instead of having the <> on the right side can do the following:

    Box<Integer> favoriteNumber = new Box<>();
  • Type Inference - Target Types

    ArrayList<String> todoList = Collections.<String>emptyList();

    Instead of having the <> on the right side can do the following:

    ArrayList<String> todoList = Collections.emptyList();