Hashset vs Treeset

后端 未结 14 1770
再見小時候
再見小時候 2020-11-22 13:38

I\'ve always loved trees, that nice O(n*log(n)) and the tidiness of them. However, every software engineer I\'ve ever known has asked me pointedly why I would u

相关标签:
14条回答
  • 2020-11-22 14:20

    The reason why most use HashSet is that the operations are (on average) O(1) instead of O(log n). If the set contains standard items you will not be "messing around with hash functions" as that has been done for you. If the set contains custom classes, you have to implement hashCode to use HashSet (although Effective Java shows how), but if you use a TreeSet you have to make it Comparable or supply a Comparator. This can be a problem if the class does not have a particular order.

    I have sometimes used TreeSet (or actually TreeMap) for very small sets/maps (< 10 items) although I have not checked to see if there is any real gain in doing so. For large sets the difference can be considerable.

    Now if you need the sorted, then TreeSet is appropriate, although even then if updates are frequent and the need for a sorted result is infrequent, sometimes copying the contents to a list or an array and sorting them can be faster.

    0 讨论(0)
  • 2020-11-22 14:20

    Message Edit ( complete rewrite ) When order does not matter, that's when. Both should give Log(n) - it would be of utility to see if either is over five percent faster than the other. HashSet can give O(1) testing in a loop should reveal whether it is.

    0 讨论(0)
提交回复
热议问题