如何在Java中修复未经检查的调用警告? [英] How to fix unchecked call warning in Java?
问题描述
这是我写的代码?
Set keys = map.keySet();
SortedSet s = new TreeSet(keys);
我得到的警告是:
warning: [unchecked] unchecked call to TreeSet(java.util.Collection<? extends E>) as a
member of the raw type java.util.TreeSet
如何摆脱编译器警告?
推荐答案
理想情况下,完全开始使用泛型。您还没有显示地图
的类型,但理想情况下您应该能够写出如下内容:
Ideally, start using generics fully. You haven't shown what the type of map
is, but ideally you should be able to write something like:
Set<String> keys = map.keySet();
SortedSet<String> s = new TreeSet<String>(keys);
在 map
的情况下类似于 Map< String,Integer>
。
如果 map
本身是一种原始类型,它更难 - 再次,最好的解决方案是开始在整个代码库中添加泛型,摆脱原始类型。当然,如果从第三方代码返回地图,那并不总是可行的。在这种情况下,当您从原始类型转换为泛型类型时,可能需要禁止一个行上的警告 - 可能通过 Collections.checkedCollection
- 但是之后,您应该能够正确使用泛型类型。例如:
If map
itself is a raw type, it's harder - again, the best fix would be to start adding generics throughout your code base, getting rid of raw types. That's not always possible if the map is returned from third party code, of course. In that case, you may need to suppress warnings on one line as you convert from raw types to generic types - possibly via Collections.checkedCollection
- but after that, you should be able to work with the generic type "properly". For example:
@SuppressWarnings("unchecked") // Just for this one statement
Collection<String> keys = Collections.checkedCollection(map.keySet(),
String.class);
// Now this statement is fully generic with no warnings
SortedSet<String> s = new TreeSet<String>(keys);
这篇关于如何在Java中修复未经检查的调用警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!