Diamond Operator in JDK 7 or Java 7 explained with example

Diamond Operator‘ or ‘<>‘ is a new feature in JDK 7 or Java 7. To understand the advantage that it offers, we will first see how a collection used to be defined using generics prior to JDK 7. We will then see how JDK 7 improves the syntax for collection definition using the ‘<>‘ operator.

Collection Definition until JDK 1.6

ArrayList stringList=new ArrayList<String>();

 
Notice in the above line of code that ‘<String>’ type is defined for the ArrayList on both sides of the equals sign. In case you wished to leave out the data type on the RHS it would be defined as –

ArrayList stringList=new ArrayList();

 
The above code would give couple of compiler warnings –

  1. That a “raw type” is getting usedArrayList is a raw type. References to generic type ArrayList<E> should be parameterized.
  2. Type Safety WarningType Safety:The expression of ArrayList needs unchecked conversion to conform to ArrayList<String>.

To avoid above warnings @SuppressWarnings({"rawtypes","unchecked"}) would need to be used on top of the method containing this code where ‘raw types’ and ‘unchecked’ prevent the warnings numbered 1 and 2 respectively.

Diamond Operator in JDK 7
JDK 7 does away with both double type definition on the LHS and RHS of the collection definition, and the overhead of adding the @SuppressWarnings through the Diamond Operator which is used as shown below –

ArrayList stringList=new ArrayList<>();

 
In the above code a Diamond(‘<>’) Operator follows the collection type ArrayList on the RHS. This code works fine in JDK 7 without giving any compiler error.

 

Digiprove sealCopyright © 2014-2019 JavaBrahman.com, all rights reserved.