- Make Map iterable.
That is, Map<K,V> should extend Iterable<Map.Entry<K,V>>, such that Map.iterator() behaves exactly like Map.entrySet().iterator() - it would save the extra ".entrySet()" in all those for-each loops, as well as making it easier to switch data structures from a List or Set to a Map. - Speaking of for-each loops, they should check for null in their iterable part. It lets you replace this code:
Iterable<E> collection = methodThatMayReturnNull();
with this, which seems to be sensible and much cleaner:
if (collection != null) {
for (E element : collection) {
//do stuff ...
}
}for (E element : methodThatMayReturnNull()) {
//do stuff ...
}
11.19.2009
Little annoyances in Java
I have a couple proposals for some syntactic sugar in Java, that fix a bunch of minor annoyances.
Subscribe to:
Post Comments (Atom)

4 comments:
Making Map iterable doesn't make much sense because someone may want to iterate over keys or they may want to iterate over values. Both are valid operations and giving one special treatment doesn't seem right and sorta makes things inconsistent.
For-each loops not executing on null collections is scary. null is not a collection, it is null. If I try to iterate over a null instead of a collection, I WANT my NullPointerException because it tells me I did something wrong. If your method that returns a collection returns null, it should be because something went wrong. If the collection does not have any elements, it should return an empty collection instead of null. This way, you can still iterate the way you want to.
And if you want to get the keys or the values out of the map, you can use Map.keySet() or Map.values(). However, you could consider a map as a set of entries, iterating over those entries would make sense - this wouldn't remove any existing functionality, just make it more convenient to iterate over the map.
As far as the for-each loop goes, you have a good point - the reason I brought it up is that I've been doing a lot of work lately with Java Web Services - if you serialize an empty map on side, it tends to come out as a null on the other ... PITA, in my opinion.
I'd recommend changing methodThatMayReturnNull() to not return null. Convention in .Net is to return the equivalent of an empty iterator. Thus, your foreach loop does nothing.
Yeah, I don't have control over the methodThatMayReturnNull() - it's a framework thing (I'm serializing an empty collection on one side, and it comes out as null on the other ...) - I think Nick was right about the NullPointerException there though.
Post a Comment