Difference Betwixt Priorityqueue As Well As Treeset Inwards Java?

The PriorityQueue too TreeSet collection classes has a lot of similarities e.g. both render O(log(N)) fourth dimension complexity for adding, removing, too searching elements, both are non-synchronized too you lot tin give the axe acquire chemical constituent from both PriorityQueue too TreeSet inwards sorted order, but in that place is primal deviation betwixt them, TreeSet is a Set too doesn't allow a duplicate element, spell PriorityQueue is a queue too doesn't conduct hold such restriction. It tin give the axe comprise multiple elements amongst equal values too inwards that instance caput of the queue volition live on arbitrarily chosen from them. Another key deviation betwixt TreeSet too PriorityQueue is iteration order, though you lot tin give the axe access elements from the caput inwards a sorted lodge e.g. caput e'er give you lot lowest or highest priority chemical constituent depending upon your Comparable or Comparator implementation but iterator returned past times PriorityQueue doesn't render whatsoever ordering guarantee.

Only guarantee PriorityQueue gives that caput volition e'er live on smallest or largest element. On the other hand, TreeSet keeps all elements inwards sorted lodge too iterator returned past times TreeSet volition allow you lot to access all elements inwards that sorted order.

This is ane of the oftentimes asked Collection interview questions too what makes it interesting is the subtle deviation betwixt a lot of similarities betwixt PriorityQueue too TreeSet.  You tin give the axe utilization ane inwards house of to a greater extent than or less other inwards to a greater extent than or less scenarios but non inwards all scenarios too that's what Interviewer is looking for when he enquire this enquiry to you lot on Interview.




Similarity betwixt PriorityQueue too TreeSet

Before looking at the deviation betwixt PriorityQueue too TreeSet, let's get-go empathise the similarities betwixt them. This volition help you lot to think of scenarios where you lot tin give the axe utilization a PriorityQueue inwards house of TreeSet or vice-versa. 

ThreadSafety
First similarities betwixt PriorityQueue too TreeSet is that both are non thread-safe, which way you lot cannot portion them betwixt multiple threads. If multiple threads are required to alter the TreeSet at the same time, too so you lot must synchronize their access externally.

Ordering
The 3rd similarity betwixt PriorityQueue too TreeSet is that both tin give the axe live on used to access elements inwards a exceptional order. TreeSet is a SortedSet, therefore it e'er keeps the elements inwards the lodge defined past times their Comparator or natural lodge if in that place is no Comparator defined, spell PriorityQueue volition e'er brand certain that caput contains the lowest or highest value depending upon the lodge imposed past times Comparator or Comparable.



Eligibility 
When I tell eligibility, which way which objects tin give the axe live on stored inwards PrioritySet too TreeSet? Is in that place whatsoever restriction or all objects are allowed? Well, in that place is, you lot tin give the axe alone shop objects which implement Comparable or Comparator inwards both PriorityQueue too TreeSet because the collection classes are responsible for keeping their commitment i.e. PriorityQueue must adjust afterwards every insertion or deletion to drib dead along the lowest or highest chemical constituent inwards caput position. Similarly, TreeSet must re-arrange elements so that they rest the sorted lodge specified past times Comparator or natural lodge imposed past times Comparable.


Performance
This is ane signal where you lot volition run across both similarity too deviation betwixt PriorityQueue too TreeSet inwards Java i.e. both provides O(log(N)) complexity for adding, removing too searching elements, but when you lot desire to take the highest or lowest priority chemical constituent too so PriorityQueue gives O(1) performance because it e'er drib dead along the chemical constituent inwards head, much similar a heap information construction i.e. minimum heap where rootage is e'er the minimum value.  If you lot are non familiar amongst heap information structure, I propose you lot reading a practiced mass on information construction e.g. Algorithms 4th Edition past times Robert Sedgewick.

 collection classes has a lot of similarities e Difference betwixt PriorityQueue too TreeSet inwards Java?


Difference betwixt PriorityQueue too TreeSet

Now, that you lot know too empathise similarities betwixt TreeSet too PrioritySet, let's run across how dissimilar they are? too why you lot cannot utilization PrioritySet inwards house of TreeSet inwards Java?


Underlying Data Structure
This get-go too initiatory off deviation is underlying information structure. PriorityQueue is a Queue too that's why it provides the functionality of FIFO information structure, spell TreeSet is a Set too doesn't render the Queue API.


Duplicate Elements
The minute deviation betwixt them tin give the axe live on derived from the get-go deviation i.e. properties of their underlying information structure. Since TreeSet is a Set it doesn't allow duplicate elements but PriorityQueue may comprise duplicates. In the instance of ties, the caput of the priority queue is chosen arbitrarily.



Performance
The 3rd deviation betwixt TreeSet too PrirityQueue comes from their relative performance. The PriorityQueue provides largest or smallest chemical constituent inwards O(1) time, which is non possible past times TreeSet. Since TreeSet is backed past times a red dark tree, the search performance volition conduct hold O(logN) time. This is why if you lot are developing an application where priority matters e.g. a chore scheduling algorithm where you lot e'er desire to execute the chore amongst the highest priority, you lot should utilization PriorityQueue information structure.


Availability
The fifth too terminal deviation betwixt PriorityQueue too TreeSet degree are that erstwhile was added inwards JDK 1.5 spell TreeSet was available from JDK 1.4 itself. This is non a real pregnant deviation inwards the historic menses of Java 8, but if you lot are working amongst legacy systems even so running on Java 1.5, a signal worth remembering.


Ordering
The quaternary difference, which is to a greater extent than subtle than you lot think because inwards similarities I conduct hold told that both are responsible for keeping to a greater extent than or less ordering. The key signal is that inwards TreeSet all elements rest inwards the sorted order, spell inwards priority queue apart from root, which is guaranteed to live on smallest or largest depending upon Comparing logic, residual of chemical constituent may or may non follow whatsoever ordering.

This way if you lot shop same elements inwards the TreeSet too PriorityQueue too iterate over them, too so their lodge volition live on different. TreeSet volition impress them inwards sorted lodge but PriorityQueue volition non until you lot are e'er getting the chemical constituent from the head.  You tin give the axe read a practiced inwardness Java mass e.g. Java: The Complete Reference, Ninth Edition to larn to a greater extent than almost PriorityQueue implementation inwards Java.

 collection classes has a lot of similarities e Difference betwixt PriorityQueue too TreeSet inwards Java?



Using PriorityQueue too TreeSet inwards Java Program

Now, let's to a greater extent than or less code to highlight the deviation betwixt PriorityQueue too TreeSet inwards Java. If you lot think the most subtle deviation I cite inwards the previous paragraph was that TreeSet keeps all elements inwards the sorted order, spell PriorityQueue alone keeps the rootage or caput into order. I hateful the lowest chemical constituent volition e'er live on at rootage inwards PriorityQueue. If you lot utilization poll() which consumes the caput too removes it, you lot volition e'er retrieve the elements inwards increasing lodge from PriorityQueue, equally shown inwards next Java program.

import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.TreeSet;  /**  * Java Program to demonstrate deviation betwixt PriorityQueue  * too TreeSet.   *   * @author WINDOWS 8  *  */ public class App {      public static void main(String args[]) {        Set setOfNumbers = new TreeSet<>();       Queue queueOfNumbers = new PriorityQueue<>();              // inserting elements into TreeSet too PriorityQueue       setOfNumbers.add(202);       setOfNumbers.add(102);       setOfNumbers.add(503);       setOfNumbers.add(33);              queueOfNumbers.add(202);       queueOfNumbers.add(102);       queueOfNumbers.add(503);       queueOfNumbers.add(33);              // Iterating over TreeSet       System.out.println("Iterating over TreeSet inwards Java");       Iterator itr = setOfNumbers.iterator();       while(itr.hasNext()){         System.out.println(itr.next());       }              // Iterating over PriorityQueue       System.out.println("Iterating over PriorityQueue inwards Java");       itr = queueOfNumbers.iterator();       while(itr.hasNext()){         System.out.println(itr.next());       }              // Consuming numbers using from caput inwards PriorityQueue       System.out.println("polling a PriorityQueue inwards Java");       while(!queueOfNumbers.isEmpty()){         System.out.println(queueOfNumbers.poll());       }   }        }  Output: Iterating over TreeSet inwards Java 33 102 202 503 Iterating over PriorityQueue inwards Java 33 102 503 202 polling a PriorityQueue inwards Java 33 102 202 503 

You tin give the axe run across that the lodge is dissimilar from the Iterator returned past times PriorityQueue too HeadSet (highlighted past times red) but when you lot utilization the poll() method to eat all elements inwards PriorityQueue, you lot conduct hold got them inwards the same lodge they were acquaint inwards TreeSet i.e. lowest to highest. This proves the signal that TreeSet keeps all elements inwards sorted order spell PriorityQueue alone aid almost the rootage or caput position. This sort of details are real of import from Java certification perspective equally well, you lot volition detect a lot of questions based upon such subtle details inwards mock exams besides equally on the existent exam.


Summary

Finally, hither is the summary of all the differences betwixt TreeSet too PriorityQueue inwards Java on the overnice tabular format for slow reference:

 collection classes has a lot of similarities e Difference betwixt PriorityQueue too TreeSet inwards Java?


That's all almost the difference betwixt TreeSet too PrirorityQueue inwards Java. Though both provides to a greater extent than or less sort of sorting capability in that place is a huge deviation betwixt the conduct of these 2 collection classes. The get-go too most of import deviation is ane is Set too other is Queue, which way ane doesn't allow duplicate spell other is FIFO information construction without whatsoever restriction on duplication.  If you lot desire to larn to a greater extent than almost advanced information construction too collection classes inwards Java, I propose to read a practiced mass inwardness Java e.g. Core Java For the Impatient past times Cay. S. Horstmann.

Further Learning
Java In-Depth: Become a Complete Java Engineer
answer)
  • Difference betwixt Hashtable too HashMap inwards Java? (answer)
  • Difference betwixt HashMap too LinkedHashMap inwards Java? (answer)
  • Difference betwixt ConcurrentHashMap too HashMap inwards Java? (answer)
  • Difference betwixt ArrayList too Vector inwards Java? (answer)
  • Difference betwixt ArrayList too LinkedList inwards Java? (answer)
  • Difference betwixt TreeMap, HashMap, too LinkedHashMap inwards Java? (answer)
  • Difference betwixt fail-fast too fail-safe Iterator inwards Java? (answer)
  • Difference betwixt HashMap, Hashtable, too ConcurrentHashMap inwards Java? (answer)
  • Difference betwixt an Array too ArrayList inwards Java? (answer)
  • Difference betwixt synchronized ArrayList too CopyOnWriteArrayList inwards Java? (answer)

  • Thanks for reading this article so far, if you lot similar this article too so delight portion amongst your friends too colleagues. If you lot conduct hold whatsoever questions or feedback too so delight drib a comment.

    Komentar

    Postingan populer dari blog ini

    Difference Betwixt Struts Validatorform Vs Validatoractionform - Interview Question

    How To Convert Inputstream To Byte Array Inwards Coffee - Two Examples

    Difference Betwixt Fileinputstream Together With Filereader Inwards Coffee | Inputstream Vs Reader