![]() ![]() This will help you to think of scenarios where you can use a PriorityQueue in place of TreeSet or vice-versa. What are similarities between PriorityQueue and TreeSetīefore looking at the difference between Priority Queue and TreeSet, let's first understand the similarities between them. You can use one in place of another in some scenarios but not in all scenarios and that's what the interviewer is looking for when he asked this question to you on Interview. ![]() This is one of the frequently asked Collection interview questions and what makes it interesting is the subtle difference between a lot of similarities between PriorityQueue and TreeSet. On the other hand, TreeSet keeps all elements in sorted order, and the iterator returned by TreeSet will allow you to access all elements in that sorted order. Only guarantee PriorityQueue gives that head will always be the smallest or largest element. It can contain multiple elements with equal values and in that case head of the queue will be arbitrarily chosen from them.Īnother key difference between TreeSet and PriorityQueue is iteration order, though you can access elements from the head in sorted order like head always give you lowest or highest priority element depending upon your Comparable or Comparator implementation iterator returned by PriorityQueue doesn't provide any ordering guarantee. both provide O(log(N)) time complexity for adding, removing, and searching elements, both are non-synchronized and you can get elements from both PriorityQueue and TreeSet in sorted order, but there is a fundamental difference between them, TreeSet is a Set and doesn't allow a duplicate element, while PriorityQueue is a queue and doesn't have such restriction. ![]() Therefore iterating over all vertices' neighbors over the course of a run of Dijkstra's algorithm takes O(|E|) time.The PriorityQueue and TreeSet collection classes have a lot of similarities e.g.
0 Comments
Leave a Reply. |