Hashset vs Treeset

后端 未结 14 1783
再見小時候
再見小時候 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:01

    HashSet is O(1) to access elements, so it certainly does matter. But maintaining order of the objects in the set isn't possible.

    TreeSet is useful if maintaining an order(In terms of values and not the insertion order) matters to you. But, as you've noted, you're trading order for slower time to access an element: O(log n) for basic operations.

    From the javadocs for TreeSet:

    This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).

提交回复
热议问题