If i create 2 lists from the same set, can I be sure that I get the same ordering in both the lists? (I do not care about the ordering as long as both the lists have the same order and I am not performing any operations on the sets between creating the two lists.)
List l = new ArrayList(set);
List l1 = new ArrayList(set);
I understand that there are guaranteed ways of creating these lists and getting the same order and that there isn't a good reason for me to create two lists this way, but I would like to know why the ordering of elements in a set would change if no modify operations are performed on it.
Edit: The set is an unordered HashSet
Unlike List, Java Set is NOT an ordered collection, it's elements does NOT have a particular order. Java Set does NOT provide a control over the position where you can insert an element. You cannot access elements by their index and also search elements in the list.
The order of elements in the set does not matter. We could just as well write S = {N ader, Buchanan, Gore, Bush}. In general, two sets are the same if and only if they have exactly the same members. “Gore ∈ S” reads “Gore is a member of the set S.” “∈” means “is a member of” or “is in”.
Set in Java doesn't maintain any order. Though Set provide another alternative called SortedSet which can store Set elements in specific Sorting order defined by Comparable and Comparator methods of Objects stored in Set.
It means that HashSet does not maintains the order of its elements. Hence sorting of HashSet is not possible. However, the elements of the HashSet can be sorted indirectly by converting into List or TreeSet, but this will keep the elements in the target type instead of HashSet type.
You will propably get the same ordering in the lists l
and l1
. But since most Sets are unordered, you have no guarantee that there will be the same order.
Technically you could write an implementation of the Set
interface which changes its order everytime any method is called. This would still fulfil the interface.
Since in the constructor new ArrayList(Collection)
the toArray
method of the collection is called, we can have a look at the Javadoc of Set#toArray()
:
Returns an array containing all of the elements in this set. If this set makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.
While the Javadoc of Set#iterator()
says there is no general guarantee:
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).
Given this, I would strongly advise you not to rely on the ordering of the lists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With