java - LinkedHashSet iteration not in ascending order? -
in following code, if parameter {1,3,2}, in while loop, 1, 3, 2.
i using linkedhashset, why order not 1, 2, 3? else need make iteration in ascending order?
cannot use treeset
add, remove, contains()
in o(log n) time.
public static void iterate(int[] num) { linkedhashset<integer> set = new linkedhashset<integer>(); (int : num) { set.add(i); } iterator<integer> iter = set.iterator(); while (iter.hasnext()) { // why same order inseration order, not assending order? int = iter.next(); } }
because linkedhashset iterates in insertion order , not sorted! javadoc:
this implementation differs hashset in maintains doubly-linked list running through of entries. linked list defines iteration ordering, order in elements inserted set (insertion-order).
you want use treeset sorted set, have @ sorted set javadoc: https://docs.oracle.com/javase/7/docs/api/java/util/sortedset.html
Comments
Post a Comment