如何擺脫本示例代碼中的警告。如何擺脫TreeMap中eclipse neon中的「空類型安全」警告
我使用Eclipse霓虹燈與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<[email protected] Entry<@Nullable Integer,@Nullable String>>'
我試圖@Nullable和的幾種組合@非空。即使? 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矮個子粘貼錯誤的代碼。
不應該'set'變量只是'Set>'?條目集中的條目可能不會爲空。 –
我先試了一下。但是錯誤在於,由於@NonNullByDefault,他無法將Set
Torge