Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does LinkedHashSet constructor preserve order

Does the constructor LinkedHashSet(Collection<? extends E> c) guarantee preserved order of its argument, assuming the argument is an ordered collection? How can we be sure of that?

The Javadoc documentation says nothing about order:

Constructs a new linked hash set with the same elements as the specified collection. The linked hash set is created with an initial capacity sufficient to hold the elements in the specified collection and the default load factor (0.75).

I don't see any reason for it to not preserve order but I want to know if it is guaranteed (for current and future implementations).

like image 782
AnnTea Avatar asked Mar 07 '23 18:03

AnnTea


1 Answers

Looking at the Java 8 implementation of java.util.LinkedHashSet you have this constructor:

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

So what is the content of addAll?

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

addAll uses a loop through the collection used in the constructor:

for (E e : c)

This means that if the collection implementation used in the constructor is ordered (e.g. java.util.TreeSet), then the content of the new LinkedHashSet instance will also be ordered.

The implementation in Java 9 is very much the same.

Yes, the order is preserved in case the incoming collection is ordered.

You can only be sure about this by checking the implementation in this specific case.

like image 51
gil.fernandes Avatar answered Mar 10 '23 09:03

gil.fernandes