![](/img/trans.png)
[英]Type safety: The expression of type Map.Entry needs unchecked conversion to conform to Map.Entry<String,CredentialParam>
[英]Java - Unchecked cast from Object to Map.Entry<String,String>
我在“Map.Entry entry =(Entry)o;”上有一個“從Object到Map.Entry的未經檢查的強制轉換”。
我認為一切正常,我可以安全地添加抑制警告,但我不確定。 這是我的代碼。
public abstract class WebPath {
protected Hashtable<String, String> wp;
public String get(String whatDoYouWant) {
for (Object o : wp.entrySet()) {
Map.Entry<String, String> entry = (Entry<String, String>) o;
if (whatDoYouWant.equals(entry.getKey())) {
return (String) entry.getValue();
}
}
return null;
}
}
謝謝大家,祝你有個美好的一天!
不要壓制警告,它給你很好的建議! 您選擇將每個條目分配給無信息的基類Object
,而不是更精確的類型Map.Entry<String, String>
。 如果您修復了for循環,則會消除警告:
for(Map.Entry<String, String> o : wp.entrySet()) {
當您獲取實例並將其強制轉換為派生類時,編譯器不喜歡它。 這是因為您無法保證該實例是該派生類。 如果你知道更好,例如在你的情況下,那很好,但這不是一般的最佳做法。
你的wp.entrySet()返回一組Map.Entry。 所以使用Map.Entry! 更好的是,如果你沒有刪除泛型類型,那么你應該:
for(Map.Entry<String, String> entry : wp.entrySet()) {
// ...
}
因為你知道它是什么類型,所以不需要拋出它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.