Je connais la différence entre hashmap (tableaux + liés) et linkedhashMap (conservez l'ordre lorsque vous le mettez);
Ma question est la suivante: entrySet et LinkedEntrySet ont-ils la même fonctionnalité que HashMap et 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);
}
}
Réponses:
5 pour la réponse № 1En regardant le code (Java 8), dans les deux cas entrySet()
retourne une instance d'une classe interne de la classe correspondante Map
la mise en oeuvre :
Pour LinkedHashMap
:
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es;
return (es = entrySet) == null ? (entrySet = new LinkedEntrySet()) : es;
}
Pour HashMap
:
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es;
return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}
Comme vous pouvez le voir, ils n’utilisent ni l’un ni l’autre LinkedHashSet
ni HashSet
. Ils ont spécifique Set
mises en œuvre.
Et la raison pour laquelle ils utilisent des implémentations internes spécifiques, il est que ces Set
s sont soutenus par le respectif Map
s, alors ils ne disposent pas de stockage propre.