Map实现类的区别

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它可以帮你将键值排序输出,默认的排序方式是进行升序排序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值