[英]What's the different between the result of HashMap.entrySet() and LinkedHashMap.entrySet(),do they have the same performance?
我知道hashmap(数组+链接)和linkedhashMap之间的区别(当你输入它时保持顺序);
我的问题是entrySet和LinkedEntrySet是否具有与HashMap和LinkedHashMap相同的功能?
Map<String,Integer> hashmap= new HashMap<>();
Map<String,Integer> linkedmap = new LinkedHashMap<>();
Set hashset = hashmap.entrySet();//EntrySet
Set linkedset = linkedmap .entrySet();//LinkedEntrySet
// Here is my test code
@Test
public void mapTest(){
Map<String,Integer> hashMap= new HashMap<>();
Map<String,Integer> linkedHashMap= new LinkedHashMap<>();
hashMap.put("1",1);
hashMap.put("3",3);
hashMap.put("2",2);
hashMap.put("5",5);
hashMap.put("8",8);
hashMap.put("6",6);
hashMap.put("7",7);
hashMap.put("4",4);
linkedHashMap.put("1",1);
linkedHashMap.put("3",3);
linkedHashMap.put("2",2);
linkedHashMap.put("5",5);
linkedHashMap.put("8",8);
linkedHashMap.put("6",6);
linkedHashMap.put("7",7);
linkedHashMap.put("4",4);//LinkedHashMapwill keep the order
Set hashSet = hashMap.entrySet();
Set linkedSet= linkedHashMap.entrySet();//the linkedSetwill keep the order too???
for (Object o : hashSet ) {
System.out.println(o);
}
for (Object o : linkedSet) {
System.out.println(o);
}
}
查看代码(Java 8),在两种情况下, entrySet()
返回相应Map
实现的内部类的实例:
对于LinkedHashMap
:
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es;
return (es = entrySet) == null ? (entrySet = new LinkedEntrySet()) : es;
}
对于HashMap
:
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es;
return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}
如您所见,它们既不使用LinkedHashSet
也不使用HashSet
。 他们有特定的Set
实现。
并且他们使用特定内部实现的原因是这些Set
由相应的Map
支持,因此他们没有自己的存储。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.