Type Inference in Java 7 is another great addition introduced to ease the developer to type redundant code. Based on the invocation, it helps Java compiler to infer the type arguments of actual definition to make invocation applicable. Inference algorithm helps compiler to find the most suitable type that can work with all of the arguments.

Type Inference in Java 7

When creating a list with Generics like below example, did you ever question yourself, why should I repeat <String, List<String>> two times and why can’t compiler can understand by itself.

[sourcecode language=”java”]
Map<String, List<String>> countryZipCodes = new HashMap<String, List<String>>();
List<Address> addressList = new ArrayList<Address>();
[/sourcecode]

I hope everyone might have thought about it that why should they repeat the types on both right hand and left hand sides. Why can’t compiler can infer the types on right hand side by looking at the left hand side? Yes, compiler will do it from Java 7.

Type Inference

Type Inference in Java 7 helps compiler to infer the type of arguments from left hand side to right hand side. It will help the developers to not repeat the same code again and can leave it to compiler to understand it.

So how can you ask compiler to do it? You just have to place Diamond Operator, which can inform compiler to use inference algorithm to infer types. Diamond operator is nothing but angular brackets facing each other as <>.

With diamond operator above example can be simplified to:

[sourcecode language=”java”]
Map<String, List<String>> countryZipCodes = new HashMap<>();
List<Address> addressList = new ArrayList<>();
[/sourcecode]

  • [tie_list type=”lightbulb”]It’s important to note that diamond operator is mandatory for Type Inference, else compiler will throw warning to ensure type safety. So declarations without Diamond operator is still legal, but it is suggested to use it to avoid unchecked conversion warning.[/tie_list]

Generic Constructors:

Till Java 6, to create objects of Generic classes, you have to specify the type during object creation.

Consider following example

[sourcecode language=”java”]
class MyClass<X> {
<T> MyClass(T t) {
// …
}
}
[/sourcecode]

To create object of above class, you should instantiate as

[sourcecode language=”java”] MyClass<Integer> object = new MyClass<Integer>(“”) [/sourcecode]

With Java 7 and above, compiler can infer the type parameter of generic classes if we use diamond operator as

[sourcecode language=”java”]MyClass<Integer> object = new MyClass<>(“”); [/sourcecode]