PQueue.offer(new Employee("BBB", 12000)) PQueue.offer(new Employee("AAA", 15000)) Let’s insert some ‘Employee’ objects into ‘pQueue’. PriorityQueue pQueue = new PriorityQueue(7, comparator) M圜omparator comparator = new M圜omparator() Let’s create a PriorityQueue of ‘Employee’ objects with ‘ M圜omparator‘ as a Comparator. Let’s define our own Comparator class ‘ M圜omparator‘ which compares the salary of two Employees.Ĭlass M圜omparator implements int compare(Employee e1, Employee e2) In the above class, toString() method is overrided so that it returns the contents of the object. Let’s define ‘Employee’ class with two attributes – ‘name’ and ‘salary’. That means head element always will be an ‘ Employee‘ object with lowest salary. We try to create a PriorityQueue of ‘ Employee‘ objects ordered in the ascending order of their salaries. In this example, we create a PriorityQueue with our own Comparator. Java PriorityQueue Example With Customized Comparator : Creating a PriorityQueue with default Comparator. The whole example can be written like this, That means elements in the ‘pQueue’ are placed in the ascending order. You can notice that always the least element is removed from the ‘pQueue’. Let’s remove the elements of ‘pQueue’ one by one using poll() method ( poll() method removes the head of the queue ). You know that head element of the PriorityQueue always will be the least element. Let’s add some elements to this PriorityQueue. PriorityQueue pQueue = new PriorityQueue() Īs we are not passing any Comparator, elements of ‘ pQueue‘ will be placed in the ascending order. In this example, we create a PriorityQueue of Integers without supplying a Comparator like this, You already know that if you don’t supply the Comparator while creating a PriorityQueue, elements will be ordered in natural ascending order. Java PriorityQueue Example With Default Comparator : You can go through the some basic definitions and properties of PriorityQueue here. In this particular article, we will discuss two examples of PriorityQueue – One with the default Comparator and another one with the customized comparator.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |