对于HashMap来说,不存在索引,也就是说不可以通过索引来访问元素,只能通过键去访问值,如要快速检索的话,HashMap性能优越。
由于没有索引,所以HashMap中元素的存放是没有顺序的。
与HashMap的不同之处在于,后者维护着一个运行于所有条目的双重链接列表。此链接列表定义了迭代顺序,该迭代顺序通常就是将键插入到映射中的顺序,如果在映射中重新插入键,则插入的顺序将不受影响。
注:HashMap和LinkedHashMap的实现都是不同步的即它们都是非线程安全的,如果多个线程同时访问链接的哈希映射,应该通过某种手段来同步线程,同步的方法:
Map map = Collections.synchronizedMap(new XXXMap());
注:JDK1.5中提供的ConcurrentHashMap是线程安全的。
测试案例:
/** * HashMap和LinkedHashMap的比较 * @author Liao * */ public class LinkedMapTest { public static void main(String[] args) { //调用测试hashMap的方法 System.out.println("===========测试HashMap============="); //因为HashMap不是线程安全的,所以在创建的时候要同步 Map<String, Integer> hashMap = Collections.synchronizedMap(new HashMap<String,Integer>()); testHashMap(hashMap); //调用测试LinkedHashpMap的方法 System.out.println("===========测试LinkedHashMap============="); //因为LinkedHashMap不是线程安全的,所以在创建的时候要同步 Map<String,Integer> linkedhashMap = Collections.synchronizedMap(new LinkedHashMap<String,Integer>()); testLinkedHashmap(linkedhashMap); } /** * 测试HashMap * @param map */ public static void testHashMap(Map<String,Integer> map){ for (int i=0; i<10; i++){ map.put(i+"", i); } //打印集合 Iterator iterator = map.entrySet().iterator(); while (iterator.hasNext()){ //获取Entry对象 Entry entry = (Entry) iterator.next(); //从Entry中获取key和value System.out.println(entry.getKey() +"==>" + entry.getValue()); } } /** * 测试LinkedHashMap * @param map */ public static void testLinkedHashmap(Map<String,Integer> map){ for (int i=0; i<10; i++){ map.put(i + "", i); } //打印 Iterator iterator = map.entrySet().iterator(); while (iterator.hasNext()){ //获取Entry对象 Entry entry = (Entry) iterator.next(); //从Entry对象中获取key和value System.out.println(entry.getKey() +"==>"+ entry.getValue()); } } }
测试结果: