HashMap和TreeMap的区别和遍历

一、HashMap和TreeMap的区别

在Java的Map接口中已经实现了两种比较常用的实现类,分别为HashMap和TreeMap。

其中HashMap通过hashcode对其内容进行快速查找,其实现是通过哈希表;而TreeMap中的所有元素都保持着某种特定的顺序,其实现运用了红黑树。

HashMap的运行速度比TreeMap快一点,这是因为它们所使用的数据结构不同的原因。

所以应尽量使用HashMap,在需要排序的Map时才使用TreeMap。


二、Map的遍历

因为Map没有继承Iterator接口,所以不能用直接使用Itreator对其进行迭代,需要借助entrySet()方法和keySet()方法。

entrySet()方法的返回值是一个Set集合,集合的类型为Map.Entry。

keySet()方法的返回值是Map中key的集合。

所以通常使用如下两种遍历方法:

第一种:

		Map<String, String> hashMap = new HashMap<String, String>();
		Iterator it = hashMap.entrySet().iterator();
		while(it.hasNext()){
			Map.Entry entry = (Map.Entry) it.next();
			Object key = entry.getKey();
			Object value = entry.getValue();
		}

第二种:

		Map<String, String> hashMap = new HashMap<String, String>();
		Set keySet = hashMap.keySet();
		Iterator it = keySet.iterator();
		while(it.hasNext()){
			Object key = it.next();
			Object value = hashMap.get(key);
		}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值