In the following code, if the parameter is {1,3,2}, in the while loop, i is 1, 3, 2.
I am already using LinkedHashSet, why is the order not 1, 2, 3? What else do I need to do to make the iteration in ascending order?
Cannot use TreeSet
as it add, remove, contains()
in o(log n) time.
public static void iterate(int[] num) {
LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
for (int i : num) {
set.add(i);
}
Iterator<Integer> iter = set.iterator();
while (iter.hasNext()) {
// WHY IS i THE SAME ORDER AS INSERATION ORDER, NOT ASSENDING ORDER?
int i = iter.next();
}
}
Because a LinkedHashSet iterates in insertion order and is not sorted! From the javadoc:
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).
You will want to use TreeSet for a sorted set, have a look at the sorted set javadoc: https://docs.oracle.com/javase/7/docs/api/java/util/SortedSet.html