先使用HashMap写一个集合看输出结果。
package cn.itcast.p1.map.demo;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
public class LinkedHashMapDemo {
/**
* @param args
*/
public static void main(String[] args) {
HashMap<Integer,String> hm = new HashMap<Integer,String>();
hm.put(7, "zhouqi");
hm.put(3, "zhangsan");
hm.put(1, "qianyi");
hm.put(5, "wangwu");
Iterator<Map.Entry<Integer,String>> it = hm.entrySet().iterator();
while(it.hasNext()){
Map.Entry<Integer,String> me = it.next();
Integer key = me.getKey();
String value = me.getValue();
System.out.println(key+":"+value);
}
}
}

是无序的输出。
再看看用LinkedHashMap 集合存入元素。
package cn.itcast.p1.map.demo;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
public class LinkedHashMapDemo {
/**
* @param args
*/
public static void main(String[] args) {
HashMap<Integer,String> hm = new LinkedHashMap<Integer,String>();
hm.put(7, "zhouqi");
hm.put(3, "zhangsan");
hm.put(1, "qianyi");
hm.put(5, "wangwu");
Iterator<Map.Entry<Integer,String>> it = hm.entrySet().iterator();
while(it.hasNext()){
Map.Entry<Integer,String> me = it.next();
Integer key = me.getKey();
String value = me.getValue();
System.out.println(key+":"+value);
}
}
}

结果是按照LinkedHashMap的特点,有序链表输出。
本文通过实例对比了HashMap和LinkedHashMap在元素存储和输出顺序上的不同。HashMap是基于哈希表实现的,输出顺序无序;而LinkedHashMap则在HashMap的基础上,通过双向链表保持了插入顺序,输出结果按插入顺序排列。
692

被折叠的 条评论
为什么被折叠?



