Set by Default Sorted or Not?

前端 未结 4 2095
半阙折子戏
半阙折子戏 2021-01-13 15:53

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(\"         


        
4条回答
  •  星月不相逢
    2021-01-13 16:05

    From Oracle documentation we can find the HashSet class implements the set interface and internally backed by Hash Table.It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. But My code Which is given bellow finds it sorted even after running number of time.

     public static void main(String[] args){
            Random rand = new Random(47);           
            SortedSet intset = new TreeSet();
            Set intsetUnsorted = new HashSet();
            for(int i=0;i<10000;i++){
                intset.add(rand.nextInt(30));
            }
            intsetUnsorted.add(500);
            for(int i=0;i<10000;i++){
                intsetUnsorted.add(rand.nextInt(30));
            }
            String version = System.getProperty("java.version");
            System.out.println("JDK version-"+version);     
            System.out.println("TreeSet o/p");
            System.out.println(intset);
            System.out.println("Hash Set o/p");
            System.out.println(intsetUnsorted);
    
        }  
    

    O/P

    JDK version-1.6.0
    TreeSet o/p
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
    Hash Set o/p
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 16, 19, 18, 21, 20, 23, 22, 25, 24, 27, 26, 29, 28, 500]
    

提交回复
热议问题