Saturday, April 5, 2008

My Java7 Wishlist regarding Collections

Update: I've implemented the features mentioned below. Read more about it at another post: Implementation of My Java7 Wishlist

There are tons of feature requests for java7. Most of the them center around closures, super-packages, extension methods, tuples, etc which are all new concepts for the language. I have been wondering why no one has bothered with improving support for some of the existing concepts/classes – in particular the syntax regarding Collection classes.

Collections have been a hot topic, although indirectly, with the introduction of generics in java 5. These classes are used more and more often in daily development – at least by me J and all my colleagues. So I am considering proposing giving the Collections citizens of java additional privileges like Arrays have receive right from the start. My wish list features mainly around syntactic enhancements to improve readability and make the code more concise (inspired by Rob’s CICE).

My first proposal revolves around making the collection instantiation syntax.
For a Collection class we might consider something similar to arrays:

Instead of:

Collection<String> c = new ArrayList();
c.add(“one”);
c.add(“two”);
c.add(“three”);

Use:

Collection<String> c = new ArrayList {“one”, “two”, “three” };

For a Map instance we might consider the javascript like syntax:

Instead of:

Map<String, Integer> m = new HashMap();
m.put(“one”, 1);
m.put(“two”, 2);
m.put(“three”, 3);

Use:

Map<String, Integer> m = new HashMap { “one”:1, “two”:2, “three”:3 };

However it becomes tricky when we wish to invoke a particular conctructor of the actual implementing class. I am yet to come up with a pretty format for that one but something like

Collection<String> c = new ( ArrayList(3) ) { “one”, “two”, “three” };
Map<String, Integer> m = new ( HashMap(5, 0.8) ) { “one”:1, “two”:2, “three”:3 };

should work fine.

My second proposal is to allow syntax to treat Maps like Arrays. After all Maps are Associative Arrays J.
So one should be able to write

m[“four”] = 4;
int i = m[“two”] ;

instead of

m.put(“four”, 4);
int i = m.get(“two”);


These help make the code compact and more readable.

I would be glad if you shared with me what you think of this proposal or if you have any similar ideas.

Update: I've implemented the features mentioned above. Read more about it at another post: Implementation of My Java7 Wishlist

--

33 comments :