3.总结
HashMap通常比TreeMap快一点(树和哈希表的数据结构使然),建议多使用HashMap,在需要排序的Map时候才用TreeMap。
package com.wzs;
import java.util.*;
public class MapTest {
public static void main(String[] args) {
// 由HashMap实现的Map对象
Map<String, String> map = new HashMap<String, String>();
Emp emp = new Emp("001", "张三");
Emp emp2 = new Emp("005", "李四"); // 创建Emp对象
Emp emp3 = new Emp("004", "王一");
map.put(emp.getE_id(), emp.getE_name());
map.put(emp2.getE_id(), emp2.getE_name()); // 将对象添加到集合中
map.put(emp3.getE_id(), emp3.getE_name());
Set<String> set = map.keySet(); // 获取Map集合中的key对象集合
Iterator<String> it = set.iterator();
System.out.println("HashMap类实现的Map集合,无序:");
while (it.hasNext()) {
String str = (String) it.next();
String name = (String) map.get(str); // 遍历map集合
System.out.println(str + " " + name);
}
// 创建TreeMap集合对象
TreeMap<String, String> treemap = new TreeMap<String, String>();
treemap.putAll(map); // 向集合添加对象
Iterator<String> iter = treemap.keySet().iterator();
System.out.println("TreeMap类实现的Map集合,键对象升序:");
while (iter.hasNext()) { // 遍历TreeMap集合对象
String str = (String) iter.next(); // 获取集合中的所有key对象
String name = (String) map.get(str); // 获取集合中的所有values值
System.out.println(str + " " + name);
}
}
}
输出结果: HashMap类实现的Map集合,无序: 004 王一 005 李四 001 张三 TreeMap类实现的Map集合,键对象升序: 001 张三 004 王一 005 李四
HashMap,TreeMap比较,布布扣,bubuko.com
原文地址:http://blog.csdn.net/adam_wzs/article/details/25080707