Does the LinkedHashSet constructor keep order

Is a constructor a LinkedHashSet(Collection<? extends E> c)guaranteed stored order of its argument if the argument is an ordered collection? How can we be sure of this?

The Javadoc documentation says nothing about the order:

Creates a new associated hash set with the same elements as the specified collection. A linked set of hashes is created with an initial set of sufficient to store items in the specified collection and default load factor (0.75).

I see no reason for him not to keep order, but I want to know if this is guaranteed (for current and future implementations).

+4
source share
2 answers

Java 8 java.util.LinkedHashSet, :

public LinkedHashSet(Collection<? extends E> c) {
    super(Math.max(2*c.size(), 11), .75f, true);
    addAll(c);
}

, addAll?

public boolean addAll(Collection<? extends E> c) {
    boolean modified = false;
    for (E e : c)
        if (add(e))
            modified = true;
    return modified;
}

addAll , :

for (E e : c)

, , , (, java.util.TreeSet), LinkedHashSet.

Java 9 .

, .

, .

+1

, , addAll:

, , .

+2

Source: https://habr.com/ru/post/1687800/


All Articles