[英]Odd behavior with Maps
我收到一個語法錯誤,我無法解決。 我使用的是Java 1.8。
import java.util.*;
public class datatypetest
{
public static void main(String args[])
{
Map map1 = new HashMap();
map1.put("1", "Deepak");
map1.put("2", "Ajay");
System.out.println(map1);
System.out.println(map1.keySet());
for (Map.Entry<String, String> entry : map1.entrySet())
{
System.out.println(entry.getKey() + "/" + entry.getValue());
}
}
}
但是我收到了這個錯誤:
incompatible types: Object can not be converted to Entry<String,String>
您創建了原始地圖:
Map map1 = new HashMap();
將其更改為:
Map<String,String> map1 = new HashMap<String,String>();
如果將地圖實例化為原始Map
,則不能在循環中使用Map.Entry<String, String>
(您只能使用原始Map.Entry
)。
您需要使用泛型來避免這種類型的沖突,即
Map<String, String> map1 = new HashMap<String, String>();
泛型提供類型安全。 此外,我在您的代碼中發現您的班級名稱沒有遵循最佳做法。 它確實必須以大寫字母開頭,因為它是整個JAVA世界的最佳實踐
試試這個
import java.util.*;
public class DataTypeTest {
public static void main(String args[]){
Map<String, String> map1 = new HashMap<String, String>();
map1.put("1", "Deepak");
map1.put("2", "Ajay");
System.out.println(map1);
System.out.println(map1.keySet());
for (Map.Entry<String, String> entry : map1.entrySet())
{
System.out.println(entry.getKey() + "/" + entry.getValue());
}
}
}
快樂編程:)
因為你已經創造了
Map map1 = new HashMap();
可以是任何類型(不僅僅是字符串)所以java不允許你向下轉換它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.