UPDATED:
Set s = new HashSet();
s.add(1);
s.add(5);
s.add(4);
s.add(9);
s.add(7);
s.add(8);
s.add("b");
s.add("a");
s.add("B");
s.add("A");
s.add("s");
s.add("x");
s.add("d");
System.out.println(s);
s.remove("b");
s.remove("d");
System.out.println(s);
Output:
[1, d, 4, b, 5, A, B, 7, a, 8, 9, s, x]
[1, 4, 5, A, B, 7, a, 8, 9, s, x]
[1, 4, 5, A, B, 7, a, 8, 9, s, x]
Need some information that Set default sort Integer value when we add but if i Add String to Set it would not sort by default.
Update: and Also Caps letter would always Sorted after runs many times.
java version "1.6.0_26" Java(TM) SE Runtime Environment (build 1.6.0_26-b03) Java HotSpot(TM) Client VM (build 20.1-b02, mixed mode, sharing)
please give me some idea. Thanks
HashSet
does not guaranteed that its contents will be sorted in any way. There is a special interface for sets that do provide such a guarantee: it's called SortedSet
:
A
Set
that further provides a total ordering on its elements. The elements are ordered using their natural ordering, or by aComparator
typically provided at sorted set creation time. The set's iterator will traverse the set in ascending element order. Several additional operations are provided to take advantage of the ordering. (This interface is the set analogue ofSortedMap
.)
In Java 6, there are two classes that implement this interface: ConcurrentSkipListSet
and TreeSet
.
No, HashSet
is not sorted - or at least, not reliably. You may happen to get ordering in some situations, but you must not rely on it. For example, it's possible that it will always return the entries sorted by "hash code modulo some prime" - but it's not guaranteed, and it's almost certainly not useful anyway.
If you need a sorted set implementation, look at TreeSet
.
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