JDK-4912961 : (coll) The set returned by TreeMap.keySet should implement SortedSet
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 1.4.2
  • Priority: P5
  • Status: Closed
  • Resolution: Won't Fix
  • OS: windows_2000
  • CPU: x86
  • Submitted: 2003-08-26
  • Updated: 2012-10-08
  • Resolved: 2006-05-19
Related Reports
Relates :  
Relates :  
Description
Name: rmT116609			Date: 08/26/2003


A DESCRIPTION OF THE PROBLEM :
I think that the Set returned by TreeMap.keySet should implement SortedSet, because it's actually a sorted Set.

ERROR MESSAGES/STACK TRACES THAT OCCUR :
C:\java\src>java Test
Exception in thread "main" java.lang.ClassCastException: java.util.TreeMap$1
        at Test.main(Test.java:7)

REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------
import java.util.*;

public class Test {
    public static void main(String[] args) {
        TreeMap map=new TreeMap();
        map.put("Hello","World");
        SortedSet keySet=(SortedSet)map.keySet();
    }
}

---------- END SOURCE ----------

CUSTOMER WORKAROUND :
Directly use the methods of TreeMap.
(Incident Review ID: 164293) 
======================================================================

Comments
WORK AROUND new TreeSet(treemap.keySet()) makes a sorted copy (but not a view) portably.
19-05-2006

EVALUATION The submitter is correct in that it would have been better to have TreeMap.keySet return SortedSet covariantly. Unfortunately, covariant return types were not available when TreeMap was designed, and the return type cannot be compatibly changed now because any subclass of TreeMap that overrode keySet would be broken. However, in mustang, we have introduced the new methods navigableKeySet and descendingKeySet which return NavigableSets and thus addresses the submitter's requirements. In prior releases, casting the return type of keySet to SortedSet will probably work, but there is no guarantee.
19-05-2006