How is this HashSet producing sorted output?

前端 未结 5 1668
旧巷少年郎
旧巷少年郎 2020-11-30 12:45

The following code produces the out put [1,2]even though hashset is not sorted.

Set set = new HashSet();
set.add(new Integer(2));
set.add(new In         


        
5条回答
  •  眼角桃花
    2020-11-30 13:44

    A HashSet as per the documentation does not guarantee any concept of order, so what you're seeing could very well change in a future update of Java.

    However, if you're wondering why Java's (as of now) specific implementation of HashSet produces the result you're seeing: it's because the Integer of value 1 hashes to a location in the internal entry table of a HashMap that comes before the location to which 2 hashes (note that a HashSet is really backed by a HashMap with arbitrary values). This makes sense since the hash code of an Integer object is just its value.

    In fact, you can see this even if you add even more numbers (within a certain range: the size of the entry table which is 16 by default):

    Set set = new HashSet<>();
    set.add(2);
    set.add(1);
    set.add(4);
    set.add(3);
    set.add(0);
    System.out.println(set);
    
    [0, 1, 2, 3, 4]
    

    Iteration over a HashSet takes place by iterating over the internal entry table, which means items earlier in the table come first.

提交回复
热议问题