今天開始學Java HashMap的簡單使用

map:鍵值對存儲數據,key,value,key必須唯一

Collection:list,set,queue  注意 Collections不能實例化

HashMap裏面有些可以操作的方法:

put(key,value):向HashMap中添加數據

可以通過實例化Collection將hashmap轉化爲hashset取出值和key

iterator():迭代器,可以迭代Collection實例



  1. hashMap:無序  
  2. treeMap:有序  
  3. demo:  
  4. public static void main(String[] args) {  
  5.         // TODO Auto-generated method stub  
  6.         HashMap<Integer, String> hm = new HashMap<Integer, String>();  
  7.         hm.put(101"張三");  
  8.         hm.put(102"李四");  
  9.         hm.put(103"王五");  
  10.         hm.put(106"趙六");  
  11.         Collection<String> c = hm.values();// 轉化爲hashSet類型  
  12.         Iterator<String> ia = c.iterator();  
  13.         System.out.print("姓名列表:");  
  14.         while (ia.hasNext()) {  
  15.             System.out.print(" " + ia.next());  
  16.         }  
  17.         System.out.print("\n學好列表");  
  18.         Collection<Integer> c2 = hm.keySet();  
  19.         Iterator<Integer> ia2 = c2.iterator();  
  20.         while (ia2.hasNext()) {  
  21.             System.out.print(" " + ia2.next());  
  22.         }  
  23.         //通過學號,查找值  
  24.         for(Integer key:c2){  
  25.             System.out.println("學號:"+key+" -->值:"+hm.get(key));  
  26.         }  
  27.     }  
  28. 輸出值:  
  29. 姓名列表: 張三 李四 王五 趙六  
  30. 學好列表: 101 102 103 106  
  31. 學號:101 -->值:張三  
  32. 學號:102 -->值:李四  
  33. 學號:103 -->值:王五  
  34. 學號:106 -->值:趙六  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章