集合框架學習之——Map
阿新 • • 發佈:2018-12-20
Map<K,V>有兩個型別引數:K
是此對映所維護的鍵的型別,V
是對映值的型別。將鍵對映到值的物件。一個對映不能包含重複的鍵;每個鍵最多隻能對映到一個值。
Map 介面提供三種collection 檢視,允許以鍵集、值集或鍵-值對映關係集的形式檢視某個對映的內容。對映順序 定義為迭代器在對映的 collection 檢視上返回其元素的順序。某些對映實現可明確保證其順序,如 TreeMap 類;另一些對映實現則不保證順序,如 HashMap 類。
注:將可變物件用作對映鍵時必須格外小心。當物件是對映中某個鍵時,如果以影響 equals 比較的方式更改了物件的值,則對映的行為將是不確定的。
如果向Map中的同一個鍵新增值,則之前的值會被覆蓋。
Map有兩個重要的實現類:HashMap,TreeMap.
一:HashMap是基於雜湊表的 Map 介面的實現。此實現提供所有可選的對映操作,並允許使用 null 值和 null 鍵。(除了非同步和允許使用 null 之外,HashMap 類與 Hashtable 大致相同。)此類不保證對映的順序,特別是它不保證該順序恆久不變。
遍歷HashMap有兩種方法。
import java.util.HashMap; import java.util.Map; import java.util.Set; public class 遍歷HashMap { public static void main(String[] args) { HashMap<Student,Integer> stu=new HashMap<>(); stu.put(new Student("南宮平",19),741); stu.put(new Student("郭玉霞",27),570); stu.put(new Student("龍布詩",57),702); stu.put(new Student("葉秋白",56),670); stu.put(new Student("梅吟雪",40),671); //1: //Set<Map.Entry<K,V>> entrySet()方法返回此對映所包含的對映關係的 Set 檢視 //然後呼叫getKey()、getValue()方法獲取此項對應的鍵和值 Set<Map.Entry<Student, Integer>> entries = stu.entrySet(); for(Map.Entry<Student, Integer> ele:entries){ System.out.println(ele.getKey()+"\t"+ele.getValue()); } System.out.println("---------------------------"); //2: //Set<K> keySet()方法返回此對映中包含的鍵的 Set 檢視。 //然後呼叫get(Object key)方法獲取指定鍵所對映的值 Set<Student> students = stu.keySet(); for(Student ele:students){ System.out.println(ele+"\t"+stu.get(ele)); } } }
執行結果:
二:TreeMap
和TreeSet類似,該對映根據其鍵的自然順序進行排序,或者根據建立對映時提供的 Comparator 進行排序,具體取決於使用的構造方法。
如果TreeMap的鍵是自定義物件,並且沒有實現Comparable介面,那麼編譯器就會報錯。
TreeMap和HashMap的遍歷方法類似,只是TreeMap的鍵如果是自定義物件時,需要自定義物件實現Comparable介面,下面用程式碼演示:
import java.util.Comparator; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class TreeMapDemo1 { public static void main(String[] args) { //自定義物件Student只有name和age兩個私有資料成員 //這裡我使用匿名內部類傳遞比較器,這個比較器是比較年齡 TreeMap<Student,Integer> treeMap=new TreeMap<>(new Comparator<Student>() { @Override public int compare(Student a, Student b) { int num=a.getAge()-b.getAge(); int num2=num==0?a.getName().compareTo(b.getName()):num; return num2; } }); treeMap.put(new Student("蘇蓉蓉",22),2); treeMap.put(new Student("姬冰雁",24),4); treeMap.put(new Student("原隨雲",22),6); treeMap.put(new Student("胡鐵花",25),3); treeMap.put(new Student("楚留香",23),5); Set<Map.Entry<Student, Integer>> entries = treeMap.entrySet(); for(Map.Entry<Student, Integer> ele:entries){ System.out.println(ele.getKey()+" "+ele.getValue()); } } }
執行結果: