如何摆脱此示例代码中的警告。
我将 Eclipse Neon 与 Java 1.8 和 org.eclipse.jdt.annotation_2.1.0 一起使用
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
@NonNullByDefault
public class NullAnnotationTest4 {
public static void main(String[] args) {
final TreeMap<@Nullable Integer, @Nullable String> treeMap = new TreeMap<>();
treeMap.put(3, "Test1");
treeMap.put(null, null);
//This produces the warning
final Set<@Nullable Entry<@Nullable Integer, @Nullable String>> set = treeMap.entrySet();
for (final Iterator<@Nullable Entry<@Nullable Integer, @Nullable String>> it = set.iterator(); it.hasNext(); ) {
final Entry<@Nullable Integer, @Nullable String> entry = it.next();
if (entry != null && entry.getKey() == null && entry.getValue() != null)
System.out.println(entry.getKey()+" is mapped to "+entry.getValue());
}
}
}
警告是:
Null type safety (type annotations):
The expression of type
'Set<Map.Entry<@Nullable Integer,@Nullable String>>'
needs unchecked conversion to conform to
'Set<Map.@Nullable Entry<@Nullable Integer,@Nullable String>>'
我尝试了@Nullable 和@NonNullable 的几种组合。即使? extends
是在类似情况下建议的那样:https ://bugs.eclipse.org/bugs/show_bug.cgi?id=507779
但是警告总是只会移动,但永远不会完全消失。
更新:
我通过使用这一行摆脱了警告:
final Set<? extends @Nullable Entry<@Nullable Integer, @Nullable String>> set = treeMap.entrySet();
但我完全不知道为什么。在我看来,我欺骗了验证器丢失了轨道或其他东西,代码真的开始变得丑陋。
完整的新代码:
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
@NonNullByDefault
public class NullAnnotationTest4 {
public static void main(String[] args) {
final TreeMap<@Nullable Integer, @Nullable String> treeMap = new TreeMap<>();
treeMap.put(3, "Test1");
treeMap.put(null, null);
final Set<? extends @Nullable Entry<@Nullable Integer, @Nullable String>> set = treeMap.entrySet();
for (final Iterator<? extends @Nullable Entry<@Nullable Integer, @Nullable String>> it = set.iterator(); it.hasNext(); ) {
final Entry<@Nullable Integer, @Nullable String> entry = it.next();
if (entry != null && entry.getKey() == null && entry.getValue() != null)
System.out.println(entry.getKey()+" is mapped to "+entry.getValue());
}
}
}
更新 2 Shorty 粘贴了错误的代码。