HashMap和TreeMap的区别和遍历

来源:互联网 发布:海洋cms采集资源 编辑:程序博客网 时间:2024/06/03 02:26

一、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);}



0 0
原创粉丝点击