hashmap對象的使用

1111111111111111111111111111111111111111111111111111111

HashMap獲取鍵和值

// 新建HashMap
HashMap map = new HashMap();
// 添加操作
map.put("one", r.nextInt(10));
map.put("two", r.nextInt(10));
map.put("three", r.nextInt(10));
// 打印出map
System.out.println("map:"+map );
// 通過Iterator遍歷key-value
Iterator iter = map.entrySet().iterator();
while(iter.hasNext()) {
Map.Entry entry = (Map.Entry)iter.next();
System.out.println("next : "+ entry.getKey() +" - "+entry.getValue());
}
// HashMap的鍵值對個數 
System.out.println("size:"+map.size());
// containsKey(Object key) :是否包含鍵key
System.out.println("contains key two : "+map.containsKey("two"));
System.out.println("contains key five : "+map.containsKey("five"));
// containsValue(Object value) :是否包含值value
System.out.println("contains value 0 : "+map.containsValue(new Integer(0)));
// remove(Object key) : 刪除鍵key對應的鍵值對
map.remove("three");
System.out.println("map:"+map );
// clear() : 清空HashMap
map.clear();
// isEmpty() : HashMap是否爲空
System.out.println((map.isEmpty()?"map is empty":"map is not empty") );
2222222222222222222222222222222222222222222222222222222

java集合類HashMap獲取鍵和值

Map<Integer,Integer> map = new HashMap<Integer,Integer>();  //創建一個HashMap  

        for(int i=0;i<10;i++){                       //爲HashMap存儲鍵值對  
            map.put(i, i);  
        }  
          
        Set<Integer> keySets = map.keySet();              //獲取鍵 的Set集合  
      
        System.out.print("Map鍵:");  
        for(Integer keySet:keySets){                    //迭代輸出鍵  
            System.out.print(keySet+" ");  
        } 


Collection<Integer> values = map.values();            //獲取HashMap值  
        System.out.print("Map值:");  
        for(Integer value:values){                  //遍歷輸出HashMap值  
            System.out.print(value+" ");  
        }  


發佈了25 篇原創文章 · 獲贊 15 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章