Sunday, March 6, 2011

Do we really need <> in the diamond operator?

As you may know, one of new features of upcoming Java 7 will be the diamond operator. Purpose of the diamond operator is to simplify instantiation of generic classes. For example, instead of

List<Integer> p = new ArrayList<Integer>();

with the diamond operator we can write only

List<Integer> p = new ArrayList<>();

and let compiler infer the value of type argument. Nice simplification. But do we really need to write <>? Isn't new ArrayList() enough? In this article, I will describe the arguments of the <> proponents and explain why I think that these arguments are not very strong. However, I also describe arguments why we need <>.

In Java 1.4, we had raw types only:

List p = new ArrayList();

Java 5 introduced generics:

List<Integer> p = new ArrayList<Integer>();

Many types in Java API were generified and even though we can still use generic types as raw types, there is no reason for this in Java 5 or newer. When generics were introduced, raw types were allowed for backward compatibility so that we could gradually and smoothly adopt generics. For example, code in Java 1.4 can be combined with new generic code because raw and generic types are allowed together. This is also expressed in the JLS (4.8 Raw Types):

"The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of genericity into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types."

Now let's go back to the diamond operator and ask again: "Do we really need <>?". The proponents of the <> syntax say that we need <> to preserve backward compatibility. Let's look at an example from the coin-dev conference:

class Foo<X> {
   Foo(X x) { }
   Foo<X> get(X x) { return this; }

class Test {
   void test() {
      Foo<?> f1 = new Foo(1).get(""); //ok - can pass String where Object is expected
      Foo<?> f2 = new Foo<>(1).get(""); //fail - cannot pass String where Integer is expected

This shows the difference between new Foo(1) and new Foo<>(1). Clearly, these two are different and if we changed the semantics of new Foo(1), it would break backward compatibility. But wait. Backward compatibility with what? Isn't line

Foo<?> f1 = new Foo(1).get("");

a little suspicious? It uses generic type in the left part and raw type in the right part. Although it is legal, it is probably either omission or malpractice. And its legality is probably only a side effect of "a concession to compatibility of legacy code".

Let's go further and look at another example from the coin-dev conference. It shows the difference between raw type and parameterized type with the diamond:

public class X<T> {
   public X(T t) { }
   public T get() { return null; }

   public static int f(String s) { return 1; }
   public static int f(Object o) { return 2; }

   public static void main(String[] args) {
      System.out.println(f(new X<>("").get()));
      System.out.println(f(new X("").get()));

Let's play with the code a bit. Let's assume that there was a library with the X class:

public class X {
   public X(Object o) { }
   public Object get() { return null; }

and some code that compiled against this library:

public class Client {
   static int f(String s) { return 1; }
   static int f(Object o) { return 2; }

   public static void main(String[] args) {
      System.out.println(f(new X("").get()));

Then, the library was generified:

public class X<T> {
   public X(T t) { }
   public T get() { return null; }

and we compiled the client project against the generified version. Now, if we changed the semantics of new X("") to new X<String>("") (or new X<>("") with the diamond syntax), the code would behave differently. So, the answer to the title question is 'yes'. If we want to stay backward compatible, we need <> and we cannot put new X("") semantically equal to new X<>("").

Other questions are how long can Java evolve and remain compatible with concessions to compatibility and whether newcomers to Java will appreciate this.


Anonymous said...

They say you need to break a few eggs to make an omlette. These don't seem like eggs we can't afford to lose.

Howard Lovatt said...

If you had a source statement then you could, e.g.:

source Java7;


System.out.println(f(new X("").get()));

Issues a warning saying that meaning has changed since Java 6. Could be suppressed with an annotation.

You could even just make the change and issue the warning without the source statement, since I think there would be very little real code broken.

However, a source statement would allow for many more advancements and wouldn't break backwards compatibility. As noted in the last sentence of the blog, backwards compatibility is a problem for Java (I would say in many areas).

Anonymous said...

Why should new X<>("") be made to work? It only works if there happens to be a constructor that includes the generic type (and then this value should also be filled in with the correct type, thus not null)

I'd say this situation should just remain as it was before the diamon operator(X becomes a raw type), or just specify the type on the constructor. The type is still only written once, so not a big issue.

In all the other situations where type can simply be obtained from the left side of the operation the code becomdes a lot cleaner.

The other example from the mailing list that was given is ArrayList x = new ArrayList(new ArrayList());
However, as also mentioned over there, that code is just plain wrong so also not a very strong argument in favour of the diamond operator.

I'm still not convinced we need it..

sboulay said...

It would certainly clean things up if we could take it out (not the feature .. just the <>).

Anonymous said...

The ideology of Java backward compatibility (every ideology) blinds eyes.
Who needs endless and efortless compatibility in reality?
From the Java begining the ideology leads Java to "drow dead legs with it". It makes Java .
There is no situations "compatibility or uncompatibility" usually.
Lets Java evolve.
If it really needed acompany Java with configurations or tools for allowing backward compatibile run or compile.

ArrayList said...

I agree this is unnecessary, simple ArrayList() would be enough and better. <> diamond operator if it just do that than its pretty useless.

airport said...

I like the new features of Java 7, but then again that was the first version that I started to use, it does seem that the old versions of just about everything make more sense than the new ones though, I dont know why they do that, just fix the bugs and leave well enough alone!! :)

Cheap Generic Viagra said...

I completely share your view points when it comes to this topic. I thought I was the alone who maneuver such a thinking process. But yeah finally I have got a company. Let’s search more on this and share over her. What say??

wallpapers said...

cool! Nice Sharing

hoang lien said...

Minecraft Skins . How do you feel if your charaters have very new and fashionable skins in many games of Minecraft at this Christmas and up-coming Tet holiday? It will be really fun. Now let me make it come true. I am so excited to be with you in every Minecraft game! 

Minecraft Mods
. Just like Skins, you seem to get so bored with some Minecraft mods you have ever used. Would you like to take part in extremely modern and great new games as well as experience the exciting atmostphere that you have never tried before? I guess all of you cannot wait more for these wonderful things. Let’s get started to join these games and I will show you how easy it is to find out the other Minecraft mods.

Minecraft Maps
. Hmmm… In Minecraft, I like this part most. Do you know why? Well, as you can see, Maps Minecraft is so great because you cannot discover any challenge in every game without Maps Minecraft. The wonderful. Minecraft Maps usually interest me so much but my PC configuration is not suitable. LOL…! However , I do not give up even no matter hard it is. Now I have much more Maps Minecraft than ever after a long time discovering. All of you are welcomed to visit my blog and take a look at these Maps Minecraft. LOL… All is for everyone who are keen on Maps Minecraft. I really hope our Minecraft community will gradually become greater and happier in near future.
Minecraft Texture Packs
. I rarely search about it , but I also have many Minecraft Texture Packs to share with you. 

Christmas and New Year are together coming! Wish you all happiness and best luck! I hope these great holidays will bring us millions of reasons to smile in life! Merry Xmas and Happy New Year!
Everything will finally be alright! Wish you a successful life! Your all
dreams will definitely come true! <3

mmo25 said...

DriveClub, Progression Studios' just lately overdue race online game, will make a look this coming year at Dsi Some retail store kiosks, and also Panasonic unveiled a youtube video these days exhibiting the game play that is to be presented.Panasonic as well as Advancement revealed DriveClub in the PS4's first appearance function inside Feb .
FIFA 15 Coins

FUT 15 Coins

Aashi siva said...

I truly appreciate this post. I’ve been looking all over for this! Thank goodness I found it on Bing. You have made my day! Thanks again! Keep update more excellent posts..

Linux Training in Chennai Velachery

Suseela Susiee said...

That is very interesting; you are a very skilled blogger. I have shared your website in my social networks..!

Online Reputation Management

jasmin said...

What a nice post is it. I like this great post due to the informative content. Keep doing the great work up. highly trained plumber tacoma

Ajay Raj said...

Nice Post...

Best Linux Training Center in Chennai
Red Hat Linux Training in Chennai
Red Hat Training
Rhce Training in Chennai

Nandhini said...

This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
Security Services in Chennai

Mahalyasree said...

Excellent goods from you, man. I’ve understand your stuff previous to and you’re just too excellent. I actually like what you’ve acquired here, certainly like what you are stating and the way in which you say it. You make it enjoyable and you still take care of to keep it sensible. I can not wait to read far more from you. This is actually a tremendous site..
Office Interior Designers in Coimbatore

Philips Huges said...

Wonderful blog.. Thanks for sharing informative Post. Its very useful to me.

Installment loans
Payday loans
Title loans

sandhosh said...

Really Good article.provided a helpful information about .keep updating...
E-mail marketing company in india

Philips Huges said...

Its a wonderful post and very helpful, thanks for all this information. You are including better information regarding this topic in an effective way.Thank you so much

Personal Installment Loans
Payday Cash Advance loan
Title Car loan
Cash Advance Loan

Sowmiya said...

Really Good blog post.provided a helpful information.I hope that you will post more updates like this.
MSBI Training in Chennai

Karthi Keyan said...

Interesting blog post.This blog shows that you have a great future as a content writer.waiting for more updates...
seo company in Chennai

KarlDeville said...

Thank you for taking the time and sharing this information with us. It was indeed very helpful and insightful while being straight forward and to the point.
mcdonaldsgutscheine | startlr | saludlimpia

Pavel Co Ebele said...

Very much useful article. Kindly keep blogging

Java Training in Chennai

Java Online Training India

vinothika said...

The blog is most inspiring one. It makes the visitor to keep visting your page again and again.

Python Training in Chennai

Abitha Chetna said...

Thanks for sharing these information.Bigdata is very nice topic.We are providing online training classes.This is just the kind of information.

Selenium Training in Chennai

Abitha Chetna said...

This blog is having the general information.Got a creative work and this is very different one.We have to develop our creativity mind.This blog helps for this. Thank you for this blog.This is very interesting and useful.

Python Training in Chennai

Ancy merina said...

Really Good blog post.provided a helpful information.I hope that you will post more updates like this.
Website designers in Bangalore
Best ECommerce Website developers in bangalore

Atom Steels said... is an online platform that allows people to find offers and the greatest deals in and around OMR. It is the directory of the business in and around omr. It helps internet users to surf the required deals and offers.

Offers in Chennai

Kalai chellam said...

Its really an Excellent post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog. Thanks for sharing....

Restaurant in OMR
Apartments in OMR
Villas in OMR
Resorts in OMR

Pallavi karthi said...

It’s amazing in support of me to have a site, which is useful in support of my know-how. thanks admin, you surely come with remarkable articles. Cheers for sharing your website page.Excellent blog here...
Research Paper Publication
Science Journal
IEEE Projects
Journal Impact Factor
Highest Impact Factor Journal

IT Tutorials said...

Thanks for your article .its very useful for everyone. Hadoop training in chennai

Arushi Chaya said...

I have really happy to these reading your post. This product control and maintenance of our health.The daily routine can assist you weight lose quickly and safely.My life is completely reworked once I followed this diet.I feeling nice concerning myself.

Herbalife in Chennai
Nutrition centers in Chennai
Weight Loss in Chennai
Weight Gain in Chennai

srisiva rs said...

All the latest updates from the Python Automationminds team. Python Automationminds lets you program in Python, in your browser. No need to install any software, just start coding straight away. There's a fully-functional web-based console and a programmer's text-editor
Phyton training in Chennai

john brito said...

This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.
rpa training in chennai
rpa training in bangalore
rpa course in bangalore
best rpa training in bangalore
rpa online training

Robotic Process Automation Tutorial said...

Thank you so much for your information,its very useful and helful to me.Keep updating and sharing. Thank you.
rpa training in chennai | rpa training in velachery | trending technologies list 2018

Roja Priya said...

Thank you for sharing your article. Great efforts put it to find the list of articles which is very useful to know, Definitely will share the same to other forums.
best openstack training in chennai | openstack course fees in chennai
java training in chennai | primavera training in chennai

Nizar niz said...

I am really happy with your blog because your article is very unique and powerful for new reader.
Click here:
selenium training in chennai | selenium course in chennai
selenium training in bangalore | selenium course in bangalore
selenium training in pune | selenium course in pune | selenium class in pune
selenium training in pune | selenium course in pune | selenium class in pune
selenium online training | selenium training online | online training on selenium

amsa leka said...

Thanks for such a great article here. I was searching for something like this for quite a long time and at last I’ve found it on your blog. It was definitely interesting for me to read about their market situation nowadays. Well written article Thank You for Sharing with Us project management courses in chennai | pmp training class in chennai | pmp training fee | project management training certification | project management training in chennai | project management certification online |

Mounika said...

I prefer to study this kind of material. Nicely written information in this post, the quality of content is fine and the conclusion is lovely. Things are very open and intensely clear explanation of issues
Python training in bangalore
Python course in pune
Python training in bangalore

hansika hans said...

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging.
Java training in Chennai | Java training in Omr

Oracle training in Chennai

Java training in Chennai | Java training in Annanagar

Java training in Chennai | Java training institute in Chennai | Java course in Chennai

Roja Priya said...

Thank you for sharing your article. Great efforts put it to find the list of articles which is very useful to know, Definitely will share the same to other forums.

best openstack training in chennai | openstack course fees in chennai | openstack certification in chennai | openstack training in chennai velachery

kavinilavu G said...

Really informative post..Thanks for sharing..keep update php training in chennai
php training in velachery chennai
php course fees in chennai
best php training institute in chennai

ais a said...

Very nice post here and thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.
Online DevOps Certification Course - Gangboard
Best Devops Training institute in Chennai

amsa leka said...

Thanks for such a great article here. I was searching for something like this for quite a long time and at last I’ve found it on your blog. It was definitely interesting for me to read about their market situation nowadays.Well written article Thank You for Sharing with Us pmp training centers in chennai| pmp training in velachery | project management courses in chennai |pmp training in chennai | pmp training institute in chennai | pmp training in chennai

nivatha said...

Were a gaggle of volunteers as well as starting off a brand new gumption within a community. Your blog furnished us precious details to be effective on. You've got completed any amazing work!

Data Science course in Indira nagar
Data Science course in marathahalli
Data Science Interview questions and answers
Data science training in tambaram | Data Science Course in Chennai
Data Science course in btm layout | Data Science training in Bangalore
Data science course in kalyan nagar | Data Science Course in Bangalore

muthu said...

Become a Data Scientist
Accelerate your career in data science by starting from basics in Statistics, Data Management and Analytics to advanced topics like Neural Networks, Machine Learning and Big Data
Earn a Scholarship of up to Rs 50,000 on enrolling. Limited seats


anushri v said...

Excellant post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.
Selenium Training in Chennai Tamil Nadu | Selenium Training Institute in Chennai anna nagar | selenium training in chennai velachery
Selenium Training in Bangalore with placements | Best Selenium Training in Bangalore marathahalli
java training in chennai | java training in chennai Velachery |java training in chennai anna nagar

SANDY said...

When I initially commented, I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several emails with the same comment. Is there any way you can remove people from that service? Thanks.
Amazon Web Services Training in Pune | Best AWS Training in Pune
AWS Online Training | Online AWS Certification Course - Gangboard
Top 110 AWS Interview Question and Answers | Advanced AWS interview Questions and Answers – AWS jobs

haripriya said...

Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.
Data Science Training in Indira nagar
Data Science training in marathahalli
Data Science Interview questions and answers
Data Science training in btm layout
Data Science Training in BTM Layout
Data science training in kalyan nagar

ragul ragul said...

This blog is the general information for the feature. You got a good work for these blog.We have a developing our creative content of this mind.Thank you for this blog. This for very interesting and useful.
Best Devops online Training
Online DevOps Certification Course - Gangboard
Best Devops Training institute in Chennai

amsa leka said...

Nice blog..! I really loved reading through this article. Thanks for sharing such a
amazing post with us and keep blogging... iot training in chennai | iot training in chennai quora | iot training and placement in chennai | iot training center in chennai | best iot training centre in chennai

Rithi Rawat said...

Outstanding blog thanks for sharing such wonderful blog with us ,after long time came across such knowlegeble blog. keep sharing such informative blog with us.

Check out : machine learning training in chennai
best training institute for machine learning
machine learning tution in chennai
artificial intelligence and machine learning course in chennai

IT Tutorials said...

Really useful information. Thank you so much for sharing.It will help everyone.Keep Post. RPA training in chennai | RPA training in Chennai with placement