close

    傳統 HashMap 必須輸入Key才能取得Value,但是常常會遇到沒有 Key 但是卻想要得到 Value ,這時可以考慮使用 HashMap 中的 keySet() 方法,要注意的是這種輸出結果的順序並不是依造放入(put)的順序,所以無法跟 ArrayList 一樣有順序性的,他只是把 HashMap 裡的 put 資料全部取出而已,這部分必須要注意。可以參考以下程式碼並比對輸出結果:

 

 import java.util.HashMap;

public class NewClass {

    public static void main(String[] args) {
        HashMap map = new HashMap();

        map.put("A", "111");
        map.put("B", "222");
        map.put("C", "333");
        map.put("D", "444");
        map.put("E", "555");
        map.put("F", "666");
        map.put("G", "777");
        map.put("H", "888");
        map.put("I", "999");


        for (Object key : map.keySet()) {
            System.out.println(key + " : " + map.get(key));
        }
    }
}


輸出結果如下:

AA11

 

 

 

 

arrow
arrow
    全站熱搜

    黃彥霖 發表在 痞客邦 留言(1) 人氣()