Saturday , August 19 2017
Home / java / Type Inference in Java 7 Example

Type Inference in Java 7 Example

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.

 Map<String, List<String>> countryZipCodes = new HashMap<String, List<String>>();
 List<Address> addressList = new ArrayList<Address>(); 

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:

 Map<String, List<String>> countryZipCodes = new HashMap<>();
 List<Address> addressList = new ArrayList<>(); 
  • 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.

Generic Constructors:

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

Consider following example

class MyClass<X> {
  <T> MyClass(T t) {
    // ...

To create object of above class, you should instantiate as

 MyClass<Integer> object = new MyClass<Integer>("") 

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

MyClass<Integer> object = new MyClass<>(""); 


About Rajesh Reddy Badam

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates.


Binary Literals Java 7 Example Tutorials

Binary literals is one of the new feature added in Java 7. We already know …

Leave a Reply

Your email address will not be published. Required fields are marked *