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.


  1. 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.

  2. Speaking of for-each loops, they should check for null in their iterable part. It lets you replace this code:
    Iterable<E> collection = methodThatMayReturnNull();
    if (collection != null) {
    for (E element : collection) {
    //do stuff ...
    }
    }
    with this, which seems to be sensible and much cleaner:
    for (E element : methodThatMayReturnNull()) {
    //do stuff ...
    }