Java 9 – Diamond Operator Enhancements | Code Factory


Index Page : Link

Donate : Link

Medium Blog : Link

Applications : Link

This enhancement is as the part of Milling Project Coin (JEP 213).

Before understanding this enhancement, we should aware Generics concept, which has been introduced in java 1.5 version.

The main objectives of Generics are:

  1. To provide Type Safety
  2. To resolve Type Casting Problems.

Case 1: Type-Safety

Arrays are always type safe. i.e we can give the guarantee for the type of elements present inside array. For example if our programming requirement is to hold String type of objects, it is recommended to use String array. For the string array we can add only string type of objects. By mistake if we are trying to add any other type we will get compile time error.

String[] s = new String[10];
s[0] = "Narendra";
s[1] = "Amit";
s[2] = new Long[3]; // CE: Type mismatch: cannot convert from Long[] to String

String[] can contains only String type of elements. Hence, we can always give guarantee for the type of elements present inside array. Due to this arrays are safe to use with respect to type. Hence arrays are type safe.

But collections are not type safe, we can’t give any guarantee for the type of elements present inside collection. For example if our programming requirement is to hold only string type of objects, and if we choose ArrayList, by mistake if we are trying to add any other type we won’t get any compile time error but the program may fail at runtime.

ArrayList i = new ArrayList();
i.add("Narendra");
i.add("Amit");
i.add(new Integer(10));
...
String s1 = (String)i.get(0);
String s2 = (String)i.get(1);
String s3 = (String)i.get(2); // RE: java.lang.ClassCastException

Hence we can’t give any guarantee for the type of elements present inside collections. Due to this collections are not safe to use with respect to type, i.e collections are not Type-Safe.

Case 2: Type-Casting

In the case of array at the time of retrieval it is not required to perform any type casting.

String[] s = new String[10];
s[0] = "Narendra";
s[1] = "Amit";
...
String str = s[0] // Type casting is not required

But in the case of collection at the time of retrieval compulsory we should perform type casting otherwise we will get compile time error.

ArrayList i = new ArrayList();
i.add("Narendra");
i.add("Amit");
...
String str1 = i.get(0); // CE: incompatible types: Object cannot be converted to String
String str2 = (String)i.get(0); // valid

Hence in Collections Type Casting is bigger headache.

To overcome the above problems of collections (type-safety, type casting), Java people introduced Generics concept in 1.5version.Hence the main objectives of Generics are:

  1. To provide Type Safety to the collections.
  2. To resolve Type casting problems.

Example for Generic Collection:

To hold only string type of objects, we can create a generic version of ArrayList as follows.

ArrayList<String> a = new ArrayList<String>();

Here String is called Parameter Type.

For this ArrayList we can add only string type of objects. By mistake if we are trying to add any other type then we will get compile time error.

a.add("Narendra");
a.add("Amit");
a.add(new Integer(3)); // CE: The method add(String) in the type ArrayList<String> is not applicable for the arguments (Integer)

Hence, through generics we are getting type safety.

At the time of retrieval it is not required to perform any type casting we can assign elements directly to string type variables.

String name1 = a.get(0); //valid and Type Casting is not required.

Hence, through generic syntax we can resolve type casting problems.

Difference between Generic and Non-Generic Collections:

ArrayList l = new ArrayList();ArrayList l = new ArrayList();
It is Non Generic version of ArrayListIt is Generic version of ArrayList
For this ArrayList we can add any type of object and hence it is not Type-Safe.For this ArrayList we can add only String type of Objects. By mistake if we are trying to add any other type,we will get compile time error.
At the time of retrieval compulsory we should perform Type casting.At the time of retrieval, we are not required to perform Type casting.

Java 7 Diamond Operator (<>):

Diamond Operator ‘<>’ was introduced in JDK 7 under project Coin.

The main objective of Diamond Operator is to instantiate generic classes very easily.

Prior to Java 7, Programmer compulsory should explicitly include the Type of generic class in the Type Parameter of the constructor.

ArrayList<String> l = new ArrayList<String>();

Whenever we are using Diamond Operator, then the compiler will consider the type automatically based on context, Which is also known as Type inference. We are not required to specify Type Parameter of the Constructor explicitly.

ArrayList<String> l = new ArrayList<>();

Hence the main advantage of Diamond Operator is we are not required to speicfy the type parameter in the constructor explicitly,length of the code will be reduced and readability will be improved.

List<Map<String,Integer>> l = new ArrayList<Map<String,Integer>>();

can be writtern with Diamond operator as follows

List<Map<String,Integer>> l = new ArrayList<>();

But until Java 8 version we cannot apply diamond operator for Anonymous Generic classes. But in Java 9, we can use.

Usage of Diamond Operator for Anonymous Classes:

In JDK 9, Usage of Diamond Operator extended to Anonymous classes also.

Anonymous class:

Sometimes we can declare classes without having the name, such type of nameless classes are called Anonymous Classes.

Thread t = new Thread() {
};

We are creating a child class that extends Thread class without name (Anonymous class) and we are creating object for that child class.

Runnable r = new Runnable() {
};

We are creating an implementation class for Runnable interface without name (Anonymous class) and we are creating object for that implementation class.

ArrayList<String> a = new ArrayList<String>() {
};

We are creating a child class that extends ArrayList class without name (Anonymous class) and we are creating object for that child class.

From JDK 9 onwards we can use Diamond Operator for Anonymous Classes also.

ArrayList<String> l = new ArrayList<>() {
};

It is valid in Java 9 but invalid in Java 8.

Demo Program - 1: To demonstrate usage of diamond operator for Anonymous Class

package com.codeFactory;

class GenericClass<T>
{
	T obj;
	public GenericClass(T obj) {
		this.obj = obj;
	}
	public T getObj() {
		return obj;
	}
	public void process() {
		System.out.println("Processing...");
	}
}

public class CodeFactory {
	public static void main(String... args) {
		GenericClass<String> g1 = new GenericClass<String>("Code") {
			public void process() {
				System.out.println("Processing.. " + getObj());
			}
		};
		g1.process();
		
		GenericClass<String> g2 = new GenericClass<>("Factory") {
			public void process() {
				System.out.println("Processing.. " + getObj());
			}
		};
		g2.process();
	}
}

Output:

Processing.. Code
Processing.. Factory

If we compile the above program according to Java 1.8version, then we will get compile time error

D:\CodeFactory\javac -source 1.8 CodeFactory.java

error: cannot infer type arguments for GenericClass<T>
              GenericClass<String> g2 = new GenericClass<>("Factory")
reason: cannot use '<>' with anonymous inner classes in -source 1.8
 (use -source 9 or higher to enable '<>' with anonymous inner classes)

Demo Program - 2: To demonstrate usage of diamond operator for Anonymous Class

package com.codeFactory;

import java.util.Iterator;

public class CodeFactory {
	public static void main(String... args) {
		String[] names = {"Narendra", "Amit", "Yogi"};
		Iterator<String> itr = new Iterator<String>() {
			int i = 0;
			@Override
			public boolean hasNext() {
				return i < names.length;
			}

			@Override
			public String next() {
				return names[i++];
			}			
		};
		while(itr.hasNext()) {
			System.out.println(itr.next());
		}
	}
}

Output:

Narendra
Amit
Yogi

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s