LinkedHashMap的Key会按照插入顺序排列,HashMap的key是无序的。
测试用例:
public void testMap()
{
// 测试key有序的map, key按插入顺序排列
System.out.println("-------------------------------Linked Map-----------------------------------");
Map<String, String> linkmap = new LinkedHashMap<String, String>();
linkmap.put("王五", "12");
linkmap.put("张小龙", "3");
linkmap.put("李四", "24");
linkmap.put("张三", "23");
Iterator<String> linkMapIt = linkmap.keySet().iterator();
while(linkMapIt.hasNext()) {
String key = linkMapIt.next();
System.out.println(key);
}
// 测试HashMap的key无序
System.out.println("-------------------------------Hash Map-----------------------------------");
Map<String, String> hashMap = new HashMap<String, String>();
hashMap.put("王五", "12");
hashMap.put("张小龙", "3");
hashMap.put("李四", "24");
hashMap.put("张三", "23");
Iterator<String> hashMapIt = hashMap.keySet().iterator();
while(hashMapIt.hasNext()) {
String key = hashMapIt.next();
System.out.println(key);
}
}