简体   繁体   中英

What's the different between the result of HashMap.entrySet() and LinkedHashMap.entrySet(),do they have the same performance?

I know the different between the hashmap(arrays + linked) and linkedhashMap(keep the order when you put in it);

My question is do the entrySet and LinkedEntrySet has the same feature as HashMap and 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);
    }
}

Looking at the code (Java 8), in both cases entrySet() returns an instance of an inner class of the corresponding Map implementation :

For LinkedHashMap :

public Set<Map.Entry<K,V>> entrySet() {
    Set<Map.Entry<K,V>> es;
    return (es = entrySet) == null ? (entrySet = new LinkedEntrySet()) : es;
}

For HashMap :

public Set<Map.Entry<K,V>> entrySet() {
    Set<Map.Entry<K,V>> es;
    return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}

As you can see, they don't use neither LinkedHashSet nor HashSet . They have specific Set implementations.

And the reason they use specific internal implementations it that these Set s are backed by the respective Map s, so they don't have storage of their own.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM