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
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
andcontains
).