Java HashMap与LinkedHashMap的区别

HashMap与LinkedHashMap是Map接口的两个实现类,它们最大的区别就是HashMap的元素是无序存放的,LinkedHashMap的元素是有序存放的,示例:

Map<String, Integer> hashMap = new HashMap<String, Integer>();
Map<String, Integer> linkedHashMap = new LinkedHashMap<String, Integer>();
for (int i = 0; i < 10; i++) {
	hashMap.put(String.valueOf(i), i);
	linkedHashMap.put(String.valueOf(i), i);
}
System.out.println("HashMap");
for (Entry<String, Integer> entry : hashMap.entrySet()) {
	System.out.println(entry.getKey() + ":" + entry.getValue());
}
System.out.println("LinkedHashMap");
for (Entry<String, Integer> entry : linkedHashMap.entrySet()) {
	System.out.println(entry.getKey() + ":" + entry.getValue());
}
输出结果:

HashMap
3:3
2:2
1:1
0:0
7:7
6:6
5:5
4:4
9:9
8:8
LinkedHashMap
0:0
1:1
2:2
3:3
4:4
5:5
6:6
7:7
8:8
9:9

之前还专门发表了一篇实现Map元素排序的博文《Java 实现Map集合排序功能》,没想到被自己拍砖了,现在想想没文化可真可怕啊。。。尴尬

你可能感兴趣的:(Java HashMap与LinkedHashMap的区别)