“集合框架”提供两种常规的Map实现:HashMap和TreeMap。和所有的具体实现一样,使用哪种实现取决于特定需要。
在Map中插入、删除和定位元素,HashMap是最好的选择。但如果要按顺序遍历键,那么TreeMap会更好。
使用HashMap要求添加的键类 明确定义了hashCode()实现(助理解:Map.keySet返回的是键的Set集合,而Set集合对hashCode实现有限制,因此作为键的类也要遵守该限制)。有了TreeMap实现,添加到映射的元素 一定是可排序的。
一、HashMap
package cn.hncu.map;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
public class MapDemo {
public static void main(String[] args) {
HashMap map=new HashMap();
map.put("1001", "张军");
map.put("1002", "张三");
map.put("1003", "王铰");
map.put("1004", "李元");
//查询1----key视图
Set keys = map.keySet();
Iterator it = keys.iterator();//是集合的查询组件
while(it.hasNext()){
String str = map.get( it.next() ).toString();
System.out.println(str);
}
System.out.println("----------------");
//查询2----entrSet视图
Set entry=map.entrySet();
it = entry.iterator();//是集合的查询组件
while(it.hasNext()){
Entry e=(Entry) it.next();
System.out.println(e.getKey()+" "+e.getValue());
System.out.println(e);
}
System.out.println("----------------");
//查询2----values视图
Collection c=map.values();
it = c.iterator();//是集合的查询组件
while(it.hasNext()){
System.out.println(it.next());
}
}
}
二、TreeMap
package cn.hncu.sort;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
public class TreeMapDemo {
public static void main(String[] args) {
TreeMap map=new TreeMap();//有排序
//HashMap map=new HashMap();没有排序
map.put("1002", "张军");
map.put("1001", "李元");
map.put("1011", "张三");
map.put("1003", "王铰");
Set set=map.entrySet();
Iterator it=set.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}