La différence entre les deux est, comme vous l'avez dit :
A LinkedHashSet
est une version ordonnée de HashSet
qui maintient une liste doublement liée à tous les éléments. Utilisez cette classe à la place de HashSet
lorsque vous vous souciez de l'ordre d'itération. Lorsque vous itérez dans un HashSet
l'ordre est imprévisible, tandis qu'une LinkedHashSet
vous permet d'itérer à travers les éléments dans l'ordre dans lequel ils ont été insérés.
Quant à votre question :
Mais dans le code source de LinkedHashSet, il n'y a que des appels aux constructeurs de HashSet.
La réponse se trouve dans quels constructeurs le site LinkedHashSet
utilise pour construire la classe de base :
public LinkedHashSet(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor, true); // <-- boolean dummy argument
}
...
public LinkedHashSet(int initialCapacity) {
super(initialCapacity, .75f, true); // <-- boolean dummy argument
}
...
public LinkedHashSet() {
super(16, .75f, true); // <-- boolean dummy argument
}
...
public LinkedHashSet(Collection<? extends E> c) {
super(Math.max(2*c.size(), 11), .75f, true); // <-- boolean dummy argument
addAll(c);
}
Et (un exemple de) HashSet
qui prend un argument booléen est décrit, et ressemble à ceci :
/**
* Constructs a new, empty linked hash set. (This package private
* constructor is only used by LinkedHashSet.) The backing
* HashMap instance is a LinkedHashMap with the specified initial
* capacity and the specified load factor.
*
* @param initialCapacity the initial capacity of the hash map
* @param loadFactor the load factor of the hash map
* @param dummy ignored (distinguishes this
* constructor from other int, float constructor.)
* @throws IllegalArgumentException if the initial capacity is less
* than zero, or if the load factor is nonpositive
*/
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<E,Object>(initialCapacity, loadFactor);
}
2 votes
Utilisez l'option Intellij(Ctrl + B) pour trouver la réponse. :)
0 votes
Bien sûr, vous avez besoin du code source joint :)