Monday, March 5, 2007

TreeMap vs PriorityQueue

Comparison

Category
TreeMap
PriorityQueue
Implementation
Uses Red-Black tree
Uses Min (max) tree
Remove Time Complexity
O(log(n))
O(log(n))
Insert Time Complexity
O(log(n))
O(log(n))
Duplicates
No
Yes
Search Time Complexity
O(log(n))
O(n)

When to use PriorityQueue?

As the above comparison shows, when you need duplicates and when you don't care about finding a particular elements by key, you should use this.

When to use TreeMap?

Again, as the comparison shows, when you need duplicates and when you need to find an element based on a particular key, use this. There are ways to put duplicates into TreeMap using a custom Comparator, but try to avoid that as it breaks the general understanding of the TreeMap for users.

3 comments: