Map集合,將key對象映射到value對象
三個主要的子類:Hashtable,HashMap,TreeMap
Hashtable:底層是哈希表數據結構,不允許使用null值,線程同步
HashMap:底層是哈希表數據結構,允許使用null值,線程不同步
TreeMap:底層是二叉樹數據結構,線程不同步,可以用於給Map集合中的鍵排序
使用keySet()方法遍歷Map集合
調用Map對象的keySet()方法,得到Set對象,這裡存儲的是所有的鍵
import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class MapDemo { /** * @param args */ public static void main(String[] args) { Map<String,String> map=new HashMap<String,String>(); map.put("name", "taoshihan"); map.put("age", "100"); map.put("gender", "female"); Set<String> keySet=map.keySet(); for(String key:keySet){ System.out.println(map.get(key)); } //TreeMap可排序 Map<StudentTreeMap,String> treeMap=new TreeMap<StudentTreeMap,String>(); treeMap.put(new StudentTreeMap("taoshihan1", 40), "陶士涵"); treeMap.put(new StudentTreeMap("taoshihan2", 30), "陶士涵2"); treeMap.put(new StudentTreeMap("taoshihan3", 50), "陶士涵3"); Set<StudentTreeMap> treeMapSet=treeMap.keySet(); for(StudentTreeMap key:treeMapSet){ System.out.println(key.name+"====="+key.age); } } } class StudentTreeMap implements Comparable<StudentTreeMap>{ public int age; public String name; public StudentTreeMap(String name,int age) { this.name=name; this.age=age; } @Override public int compareTo(StudentTreeMap o) { if(o.age<this.age){ return 1; }else{ return -1; } } }