Cast TreeMap.Submap 返回:SortedMap,返回TreeMap

发布于 2024-10-04 04:17:48 字数 1013 浏览 2 评论 0原文

这对我来说似乎太棘手了,无法正确执行此操作。

我有一个 TreeMap,我正在其中获取一个子图:

        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;
        } 

这按预期工作,但是当我将排序后的地图投射回 (TreeMap) 我收到以下错误:

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

任何帮助都会很棒。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

挥剑断情 2024-10-11 04:17:48

问题正是错误所说的:返回的子图不是标准的 TreeMap,它是实现定义的内部类的实例。如果您查看 subMap 的声明:

public SortedMap subMap(Object fromKey, Object toKey)

它保证返回的对象实现 SortedMap 接口,因此这是您唯一可以安全地转换到的对象。

话虽如此,没有理由实际转换为 TreeMap,因为它不提供任何优于 SortedMap 的附加功能。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文