在转换为超类列表时,Java 中未检查的转换
在我的 Java 程序中,我需要转换 List
扩展为 List
。如果我直接进行强制转换,编译器会抱怨(显示警告)存在未经检查的强制转换。尽管我可以确定所有对象都可以转换为其超类,但编译器不会注意到它并报告未经检查的强制转换。我怎样才能摆脱警告?除了@SupressWarnings(“unchecked”)还有其他方法吗?
PS:代码工作正常,我只是好奇是否有更好的方法。
编辑:
解决方案:只有当他确定将来不会更改列表时,才应该进行这种类型的转换。但是,当我们将单个对象从列表中取出时,最好对它们进行强制转换。
In my Java program, I need to cast an object of type List<? extends SomeBaseClass>
to List<SomeBaseClass>
. If I cast it directly the compiler complains (shows a warning) that there is an unchecked cast. Even though I can be sure that all the objects can be converted to their superclass, the compiler does not notice it and reports an unchecked cast. How can I get rid of the warning? Is there any other way than @SupressWarnings("unchecked")?
P.S.: The code works fine, I am just curious whether there is a better way of doing things.
Edit:
Solution: One should only do this type of cast if he is sure the he will not change the list in the future. But it is better to cast individual objects when we take them out of the list.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编译器会抱怨,因为如果您将
SomeBaseClass
类型的对象添加到List
列表中,则可能会“违反”List
列表。这里有一个例子,当
Number
代表你的SomeBaseClass
时:如果你的情况没有办法解决这个问题,我相信
@SuppressWarnings("unchecked")< /code> 是你最好的选择。
The complier complains since if you add an object of type
SomeBaseClass
to yourList<SomeBaseClass>
list, you may "violate" the content of yourList<? extends SomeBaseClass>
list.Here in an example when
Number
figures as yourSomeBaseClass
:If there is no way around this in your case, I believe the
@SuppressWarnings("unchecked")
is your best option here.你试图做的事情是不安全的。考虑这个简单的例子:
What you're trying to do is unsafe. Consider this simple example:
你情绪低落,这是一种不好的做法。尝试重构您的代码以避免这种转换。当然,在这种情况下您不应该抑制警告。
You're downcasting, which is a bad practice. Try to refactor your code to avoid this casting. And of course you should not suppress warnings in this case.