Victor
Victor

Reputation: 17077

java retrieve objects from a Set

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?

Upvotes: 0

Views: 1276

Answers (6)

Johannes Weiss
Johannes Weiss

Reputation: 54001

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)

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691625

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).

Upvotes: 2

Yuriy Zubarev
Yuriy Zubarev

Reputation: 2871

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.

Upvotes: 0

John B
John B

Reputation: 32949

Yes it does depend on the implementation you choose. HashSet will not guarantee order but LinedHashSet will.

Upvotes: 0

soulcheck
soulcheck

Reputation: 36767

Depends on Set implementation. LinkedHashSet does exactly that.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499770

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.

Upvotes: 9

Related Questions