Reputation: 1524
Is there any way that I can get a Java Set object (not a SortedSet) to iterate over its elements in the same order every time that I run the program. (The elements are the same for each run.) I am trying to debug my program but I'm having trouble reproducing my error because the iterator returns the values in a different order each time. Thanks.
Upvotes: 3
Views: 1836
Reputation: 346377
LinkedHashSet
iterates in insertion order.
See the javadocs for more information: https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashSet.html
Upvotes: 5
Reputation: 30032
Use a LinkedHashSet
and the iteration order should be the same (it is just a HashSet backed by a LinkedList).
Upvotes: 2