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