In Java 5, If i have a Set, and i add two objects to the Set. When I retrieve the objects, will it give me back in the same order as I added? I am not able to find the answer to this. Does it depend on which Set implementation I use?
6 Answers
Yes, it depends on which implementation you use. For example, LinkedHashSet will preserve insertion order:
Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)
... but HashSet won't:
It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.
Comments
Straight from the documentation:
The elements are returned in no particular order (unless this set is an instance of some class that provides a guarantee).
Comments
Yes it does depend on the implementation you choose. HashSet will not guarantee order but LinedHashSet will.
Comments
JavaDocs is your best friend. It's implementation specific. For example:
java.util.Set:
Iterator<E> iterator();
Returns an iterator over the elements in this set. The elements are returned in no particular order (unless this set is an instance of some class that provides a guarantee).
and
java.util.TreeSet:
public Iterator<E> iterator();
Returns an iterator over the elements in this set in ascending order.
Comments
The Set interface itself is for unordered container implementations. But there might be implementations of Set that do return the elements in a particular order.
Also see the documentation of Set.iterator:
Returns an iterator over the elements in this set. The elements are returned in no particular order (unless this set is an instance of some class that provides a guarantee)
Set's documentation. See docs.oracle.com/javase/6/docs/api/java/util/Set.html