ordering a hashset example?

前端 未结 3 1234
一向
一向 2020-12-15 05:27

I need an example on how to use a comparable class on a HashSet to get an ascending order. Let’s say I have a HashSet like this one:



        
3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-15 06:13

    HashSet "makes no guarantees as to the iteration order of the set." Use LinkedHashSet instead.

    Addendum: I would second @BalusC's point about implementing Comparable and express a slight preference for LinkedHashSet, which offers "predictable iteration order ... without incurring the increased cost associated with TreeSet."

    Addendum: @Stephen raises an important point, which favors @BalusC's suggestion of TreeMap. LinkedHashSet is a more efficient alternative only if the data is (nearly) static and already sorted.

提交回复
热议问题