Cast TreeMap.Submap 返回:SortedMap,返回TreeMap
这对我来说似乎太棘手了,无法正确执行此操作。
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题正是错误所说的:返回的子图不是标准的 TreeMap,它是实现定义的内部类的实例。如果您查看
subMap
的声明:它保证返回的对象实现
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 ofsubMap
: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 aSortedMap
does.