簡體   English   中英

HashMap.entrySet()和LinkedHashMap.entrySet()的結果有什么不同,它們是否具有相同的性能?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM