未经检查的强制转换:在这种情况下有办法避免吗?
我遇到的情况导致出现未经检查的强制转换警告。我知道我可以使用抑制警告,但我的直觉告诉我有一种方法可以通过改变我编码此代码片段的方式来避免它。然而,我似乎无法让解决方案浮出水面,只能用一双新的眼睛来解决。
//function removes elements from input, orders them and re-adds them
private <E extends Bus> int orderBuses(ArrayList<E> busList) {
Bus busToAdd = null;
...
busList.add((E) busToAdd);
return 0;
}
使用多个列表调用该函数,每个列表都包含一个扩展 Bus 的类。 BusToAdd 上使用了几个属于 Bus 一部分的函数,因此使用类型 E 不起作用。
关于如何在不必抑制警告的情况下重组它的任何建议?
编辑:发现我可以使用 E 作为总线列表,但最终不得不强制转换我分配给它的总线,这会导致相同的警告。我可以尝试在所有用途中使用 E 而不是 Bus,我会在测试后进行更新。
I have a situation that is causing an unchecked cast warning. I know I can use supress warnings, but my instinct tell me there is a way to avoid it by changing how I've coded this snippet. I can't, however, seem to get the solution to surface and could do with a fresh set of eyes.
//function removes elements from input, orders them and re-adds them
private <E extends Bus> int orderBuses(ArrayList<E> busList) {
Bus busToAdd = null;
...
busList.add((E) busToAdd);
return 0;
}
The function is called with several lists, each containing a class that extends Bus. Several functions are used on busToAdd that are part of Bus so using type E wouldnt work.
Any suggestions on how to restructure this without having to suppress warnings?
edit: Found I can use E for busList, but end up having to cast the buses I assign to it which leads to the same warning. I can try using E for all uses instead of Bus, I'll update when I have tested it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么使用
E
在这里不起作用?您说您正在使用属于
Bus
一部分的一些方法,但由于E extends Bus
您应该能够调用所有Bus
' 以及E
上的方法。Why wouldn't using
E
not work here?You say that you're using some methods that are part of
Bus
, but sinceE extends Bus
you should be able to call all ofBus
' methods onE
as well.您应该能够在方法主体中用
E
替换对类型Bus
的引用。那么就不会有警告了。例子:
You should be able to replace references to the type
Bus
byE
in the body of your method. Then there would be no warning.Example: