Reputation: 532
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).
Upvotes: 6
Views: 3909
Reputation: 14611
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.
Upvotes: 5
Reputation: 53829
It preserves the order returned by the iterator of the collection as it interntally uses addAll
:
iterates over the specified collection, and adds each object returned by the iterator to this collection, in turn.
Upvotes: 3