Diamond Operator in Java 9 | Enhancements You Must Know

Diamond Operator in Java 9 | Enhancements You Must Know

As we all know that Sun Micro System is now working on a project which is called Milling Project Coin(JEP 213)

And as part of that project, there is an enhancement in Diamond Operator.

We can proceed with this enhancement But we want to make sure you know the earlier concept of Diamond Operator.

I am going to take you through some steps of questions and answer which is apart of this tutorial only.

The first Question, I want to ask you do you know the Generics Concept?

What do you mean by Generic Concept?

Generic Concept was introduced in Java 1.5 version.

The main objective of introducing these concepts are

1.To provide Type-Safety

2.To Provide Type-Casting

Let’s refresh the concept of both Type-casting and Type-Safety in our way.

TYPE-SAFETY:

When Type-safety comes, we mean to say what type of element you add and still, the execution continues smoothly.

An array is always Type-safe because whenever we are creating an array we decide at that time only what type of element we can add.

Suppose we are creating an array:

            Integer [] arr =new Integer[5];

Integer is the type of this array and We can only add Integer type element. If We will try to add some other type of String then =>

It will give :

Type mismatch: cannot convert from String to Integer

Diamond Operator in Java 9 | Enhancements You Must Know

 

You saw how adding String to an Integer array gave a compilation error, so If you want to add String then you will have to take a String Array.

After all this, We can say that Array is Type-Safe and we require to add the only respective type of element based on array type.

But Now we have to talk about the most used and important concept used in real time i.e Collection.

You might be familiar with the term Collection :

A collection is the representation of a group of elements as a single entity.

Collections are not Type-Safe that we cannot be sure about the type of element that collection contains.

Let’s see the example in the screenshot below:

Diamond Operator in Java 9 | Enhancements You Must Know

Whats happening here:

We have a created an ArrayList and we have added two elements one of Integer type and another of String type.

While adding it has gone smoothly but while retrieving the list we are getting a compilation error:

Type mismatch: cannot  convert from Object to String and you get a compiler suggestion to cast it to String or you

can change the type of s1 to Object then only you will be able to retrieve the data.

The problem with this is that at runtime this program will fail if we have not tried retrieving.

Hence we are not sure the safety of the type of Collection i.e Collection is not type-safe.

 

Now Le’s talk about the second point Type-Casting.

TYPE-CASTING

In case of Array, We don’t need to perform Type-Casting while retrieving data. Let’s See an example:

Diamond Operator in Java 9 | Enhancements You Must Know

Here we can see that Type-Casting is no required and we are easily able to perform the retrieval operation without any error.

But In Case of Collection, We Saw in the above example of Type-Safety, While performing the retrieval operation we

have seen the compilation error and it is asking us to cast into Object Type.

Refer the fig a. for more clarity.

After all this, we found that Type-Casting is the biggest problem for any developer and resolving this compilation error is so much time taking that you have to take care of much more thing.

To Overcome this problem in Collection, Sun Microsystem came with the concept of Generics in Java 1.5.

Now you got the answer to your question  What is objective and What does Generics do?

Let’s See After Generics Concept came into existence, How are we going to use Collection.

Diamond Operator in Java 9 | Enhancements You Must Know

What’s Happening Here:

We have created a List of Type String by using the concept of generics.

When we are trying to add Integer to this list, we see compilation error :

The method add(int, String) in the type List<String> is not applicable  for the arguments (int)

With the help of generics, Type-safety issue is not there now.

At the time of retrieval, we don’t need to perform Type-Casting and We can do assignment error-free.

Diamond Operator in Java 9 | Enhancements You Must Know

Difference Between Generic and Non-Generic Collection?

1.    Generic Collection representation:

                           List<String> list =new ArrayList<String>();

Non-Generic Collection representation:

                          List list =new ArrayList();

2. Type -Casting is not required in Generic Collection But In Non-Generic Collection, Type-Casting is required.

3. Generic collection doesn’t have a problem of Type-Safety But Non-Generic Collection have the problem of Type-Safety

 

Diamond Operator <> introduced in Java 7

Let’s talk about Diamond Operator, Under the project coin in JDK 7 Version, Diamond operator was introduced.

The objective of Diamond operator is to instantiate generic classes easily.

Earlier what we programmer had to face or do, We need to explicitly include the Type of generic class in the Type Parameter of the constructor.

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


Whenever we are using Diamond operator, then compiler will consider the type automatically based on context,

which is also known as Type-Inference. We don’t need to specify the Type-Paramter of the Constructor explicitly.

                          ArrayList<String> list =new ArrayList();

This concept is that we don’t need to specify Type-Parameter on another side, Compiler will take care of it.

We can reduce the developer’s work and increase the readability.

Let’s see an example:

Diamond Operator in Java 9 | Enhancements You Must Know

I hope the concept of Generics and Type-Inference are clear to you guys.

Now, It is the right time to talk about the enhancement of Diamond Operator in Java 9.

 

But till Java 8, Diamond Operator cannot be applied to Annonymous Generic Class. But In Java 9  Yes we can apply this concept.

Anonymous Class

You must be knowing the concept of Anonymous class, It is the class having no name which can be used to perform some operation and later it’s existence is not required.

    1.            Thread t= new Thread()

                 {

                 };
     2.         Runnable r =new Runnable()
                {
                };
    

Here we are creating a child class that extends Thread Class without name i.e Annonymous class and we are creating an object of that child class.

            3. ArrayList<String> list =new ArrayList()

                  {

                 };

This expression is not valid in Java 8 but this can be done in Java 9.

Example 1:

package com.amitclive.diamond;

public class TestGenerics<T> {
 T obj;
public TestGenerics(T ob) {
 this.obj = ob;
 }

public T getObj() {
 return obj;
 }

public void process() {
 System.out.println("processing method");
 }

public static void main(String[] args) {
 TestGenerics<String> test1 = new TestGenerics<String>("string1") {
 public void process() {
 System.out.println("processing method: " + getObj());
 }
 };
 test1.process();
 TestGenerics<String> test2 = new TestGenerics<String>("string2") {
 public void process() {
 System.out.println("processing method: " + getObj());
 }
 };
 test2.process();
 }
}

Diamond Operator in Java 9 | Enhancements You Must Know

 

We executed the above program in Java 8 Now we made some changes and it gave us compilation error:

Diamond Operator in Java 9 | Enhancements You Must Know

 

It gives an error like this:

<>’ cannot be used with anonymous classes

Example2:

package com.amitclive.diamond;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class TestGenerics<T> {
 public static void main(String[] args) {
 String [] words ={"A","B","C","D","E"};
 Iterator<String> itr =new Iterator<String>() {
 int i=0;
 public boolean hasNext(){
 return i<words.length;
 }
 public String next(){
 if(!hasNext()){
 throw new NoSuchElementException();
 }
 return words[i++];
 }
 };
 while(itr.hasNext()){
 System.out.println(itr.next());
 }
 }
}

Diamond Operator in Java 9 | Enhancements You Must Know

 

 

NOTE:
In the next version of java, we will see Partial Diamond operator as part of the project “AMBER” Stay tuned to this blog. We will keep you updated. Subscribe to our newsletter. Thank you for visiting our Diamond Operator in Java 9 | Enhancements You Must Know blog, See you in next blog.

Amit is a software developer by profession. He is passionate about all the technologies which can be used to build an application like java related technologies and many more and loves to implement it his career or for knowledge purpose and share his experience with you all. To know more see the About me profile.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.