Java程式設計基礎(3)——字典型別
阿新 • • 發佈:2019-01-23
今天,要用到字典型別,所以就查了了一下,直接上原始碼:
Individual indiv = new Individual(); //Individual是一個類,自己建立的,這裡就不寫具體內容了,只是想說以下,value值可以是任何型別 indiv.Fitness = 111; //這是定義value值 LinkedList<String> str = new LinkedList<String>(); str.add("+"); //定義key值 Map<LinkedList<String>, Individual> hashmap = new HashMap<LinkedList<String>, Individual>(); //定義字典 hashmap.put(str, indiv); //put方法新增資料 System.out.println(hashmap.get(str).Fitness); //get方法讀取資料
map就是字典型別,但是它就像list一樣,還可以細分好幾個類,具體可以參考以下部落格的介紹:
雜湊字典中遍歷刪除某項
Map<String, String> m = new HashMap<String, String>(); m.put("1", "張三"); m.put("2", "王五"); m.put("3", "張三"); System.out.println(m.size()); Iterator<Map.Entry<String, String>> it = m.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); //不斷迭代詞典 if (entry.getValue().equalsIgnoreCase("張三")) { it.remove(); //如果詞典中包含張三,就將這一樣移除 } } System.out.println(m.size()); //檢查對映對的大小,看看是否已經被刪除 System.out.println(m.containsValue("張三"));
顯示結果為: