Set by Default Sorted or Not?

前端 未结 4 2089
半阙折子戏
半阙折子戏 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:23

    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.

提交回复
热议问题