Question

This seems too tricky for me to be doing this correctly.

I have a TreeMap<Double, (user-defined)Object>, of which I am taking a submap:

        public static reqObj assignObj(reqObj vArg, int startDate, int endDate){
                reqObj vOut=new reqObj();



                if (keyAt(vArg.requestObject,startDate)>-1 && keyAt(vArg.requestObject,endDate)>-1){
                    System.err.println(keyAt(vArg.requestObject,startDate));
                    System.err.println(keyAt(vArg.requestObject,endDate));

                    //vOut.requestObject=(TreeMap<Double, dayObj>)

                    vArg.requestObject.subMap(
                            keyAt(vArg.requestObject,startDate),
                            keyAt(vArg.requestObject,endDate));

                }

                return vOut;
        } 

This works just as expected, but when I go to cast my sorted map back to (TreeMap) I get the following error:

  java.lang.ClassCastException: java.util.TreeMap$SubMap

Any help would be great.

Was it helpful?

Solution

The problem is exactly what the error says: the returned submap is not a standard TreeMap, it is an instance of an implementation-defined inner class. If you look at the declaration of subMap:

public SortedMap subMap(Object fromKey, Object toKey)

all it guarantees is that the returned object implements the SortedMap interface, so that's the only thing you can safely cast to.

That being said, there is no reason to actually cast to a TreeMap because it doesn't provide any additional functionality over what a SortedMap does.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top