Map集合有很多的实现子类,包括HashMap、LinkedHashMap、Hashtable、TreeMap,那么它们之间有什么区别呢,看下面的代码:
package com.repair.work.action; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; /** * 测试Map类 * * @author Administrator * */ public class MapTest { public static void main(String[] args) { Map<Integer, String> map = new HashMap<Integer, String>(); map.put(6, "apple"); map.put(3, "banana"); map.put(4, null); System.out.println("---HashMapTest----"); for (Iterator<Integer> it = map.keySet().iterator(); it.hasNext();) { Integer key = (Integer) it.next(); System.out.println(key + "--" + map.get(key)); } map = new LinkedHashMap<Integer, String>(); map.put(6, "hello"); map.put(2, "world"); map.put(3, "welcome"); System.out.println("---LinkedHashMapTest----"); for (Iterator<Integer> it = map.keySet().iterator(); it.hasNext();) { Integer key = (Integer) it.next(); System.out.println(key + "--" + map.get(key)); } map = new TreeMap<Integer, String>(); map.put(6, "hello"); map.put(2, "world"); map.put(3, "welcome"); System.out.println("---TreeMapTest----"); for (Iterator<Integer> it = map.keySet().iterator(); it.hasNext();) { Integer key = (Integer) it.next(); System.out.println(key + "--" + map.get(key)); } map = new Hashtable<Integer, String>(); map.put(6, "apple"); map.put(3, "banana"); map.put(2, "pear"); System.out.println("---Hashtable----"); for (Iterator<Integer> it = map.keySet().iterator(); it.hasNext();) { Integer key = (Integer) it.next(); System.out.println(key + "--" + map.get(key)); } } }
输出结果:
---HashMapTest----
3--banana
4--null
6--apple
---LinkedHashMapTest----
6--hello
2--world
3--welcome
---TreeMapTest----
2--world
3--welcome
6--hello
---Hashtable----
6--apple
3--banana
2--pear
由此可见:HashMap是杂乱无序的,它与Hashtable的区别是一个线程同步的,一个不是线程同步的,而且HashMap的键和值都可以为null,而Hashtable的键或者值是不能为null的,一为null就会抛出NullPointerException,LinkedHashMap它是有顺序的,根据你put进去的顺序进行输出,相当与一个栈,先put进去的最先输出来
TreeMap它可以帮你将键值排序输出,默认的排序方式是进行升序排序