JDK-6974880 : (coll) Collections.emptyMap() should return NavigableMap
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 6u21
  • Priority: P4
  • Status: Resolved
  • Resolution: Won't Fix
  • OS: windows_xp
  • CPU: x86
  • Submitted: 2010-08-05
  • Updated: 2013-07-18
  • Resolved: 2013-07-18
Related Reports
Relates :  
Description
A DESCRIPTION OF THE REQUEST :
The method Collections.emptyMap() was introduced as a typesafe alternative to using Collections.EMPTY_MAP. However, sometimes interfaces require a SortedMap. In these cases, we have to handle the creation of an empty map ourselves, since the map returned by emptyMap() doesn't implement the SortedMap interface.

Currently the declaraition of emptyMap() is this:
    static <K,V> Map<K,V> emptyMap() { ... }
this should be changed to
    static <K,V> SortedMap<K,V> emptyMap() { ... }


JUSTIFICATION :
Code to create empty SortedMap instances would be less verbose and easier to read.

Performance could benefit too, since currently the shorthand would be to call i.e. new LinkedMap() instead of emptyMap(), which actually involves unnecessary object creation (emptyMap() always just returns a reference to the same immutable object).

Only problem I can see is with methods that have overloads for Map and SortedMap parameters.


EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
The following should work:

class A {
  void foo(SortedMap<String,String> map) {}

  void bar() {
    foo(Collections.<String,String>emptyMap());
  }
}

ACTUAL -
Above example gives a compilation error.

---------- BEGIN SOURCE ----------
import java.util.Collections;
import java.util.SortedMap;

class A {
  void foo(SortedMap<String,String> map) {}

  void bar() {
    foo(Collections.<String,String>emptyMap());
  }
}
---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
class A {
  void foo(SortedMap<String,String> map) {}

  void bar() {
    foo(new LinkedMap<String,String>());
  }
}

Comments
We can't change the signature of Collections.emptyMap() and for serialization compatibility don't want to change the class returned. JDK-7129185 recently added Collections.emptySortedMap() and emptyNavigableMap() methods. If desired you can refactor to use these methods instead.
18-07-2013