Overview

Diamond operator aka diamond syntax was introduced in Java 7 as a new feature. Purpose of diamond operator is to simplify the use of generics when creating an object.

It avoids unchecked warnings in a program as well as reducing generic verbosity by not requiring explicit duplicate specification of parameter types.

Raw Types prior to Java 5

Before Java 5, the collections API supports only raw types. There was no way for type arguments be parameterized when constructing a collection.

The above code runs just fine, but suppose you also have the following:

Now we run into trouble at run-time, because the list contains something that isn’t an instanceof String.

Presumably, if you want names to contain only String, you could perhaps still use a raw type and manually check every add yourself, and then manually cast to String every item from names.

Generics from Java 5

Raw types refer to using a generic type without specifying a type parameter. For example, List is a raw type, while List<String> is a parameterized type.

When generics were introduced in JDK 1.5, raw types were retained only to maintain backwards compatibility with older versions of Java.

At line 2, we have specified the parameterized type in the constructor, which can be somewhat unreadable.

Generics exist to provide compile-time protection against doing the wrong thing.

Diamond Operator from Java 7

With Java 7, the diamond operator makes this shorter and simpler. It also adds type inference and reduces the verbosity.

It becomes even more useful with more complex data types, such as, a List of Map objects as follows:

Type inference is supported only if the parameter type of the constructor is obvious. For example, if we use the diamond operator without specifying a type for the identifier shown as follows, we will get a series of warnings:

Compiling the program with –Xlint:unchecked, results in the following warnings:

These warnings will go away if the data type is specified as follows:

Conclusion

Raw types in Java effectively only exist for compatibility with pre-generics code and should never be used in new code unless you absolutely have to.

Generics allow us to keep the safety of generics with almost the same effort as using the raw type.

It's good to share...Share on FacebookTweet about this on TwitterShare on LinkedInPin on PinterestShare on Google+Email this to someone

Leave a Reply

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