Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set by Default Sorted or Not?

Tags:

java

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

like image 864
Ravi Parekh Avatar asked Oct 07 '11 09:10

Ravi Parekh


2 Answers

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 a Comparator 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 of SortedMap.)

In Java 6, there are two classes that implement this interface: ConcurrentSkipListSet and TreeSet.

like image 97
NPE Avatar answered Sep 18 '22 13:09

NPE


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.

like image 30
Jon Skeet Avatar answered Sep 18 '22 13:09

Jon Skeet