Monday, September 4, 2017

Java - PriorityQueue Class

Source Link:
https://www.tutorialspoint.com/java/util/java_util_priorityqueue.htm

Some Useful Methods:

boolean add(E e)
This method inserts the specified element into this priority queue.

void clear()
This method removes all of the elements from this priority queue.

boolean contains(Object o)
This method returns true if this queue contains the specified element.

boolean offer(E e)
This method inserts the specified element into this priority queue.

E peek()
This method retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.

E poll()
This method retrieves and removes the head of this queue, or returns null if this queue is empty.

boolean remove(Object o)
This method removes a single instance of the specified element from this queue, if it is present.

int size()
This method returns the number of elements in this collection.

Object[] toArray()
This method returns an array containing all of the elements in this queue.

Example: 
package com.tutorialspoint;
public class PriorityQueueDemo {
   public static void main(String args[]) {
   // create priority queue
   PriorityQueue < Integer >  prq = new PriorityQueue < Integer > (); 
       
   // insert values in the queue
   prq.add(6);  
   prq.add(9);
   prq.add(5);
   prq.add(64);
   prq.add(6);
      
   System.out.println ( "Priority queue values are: "+ prq);
      
   // get objects from the queue
   Object[] arr = prq.toArray(); 
  
   System.out.println ( "Value in array: ");
      
   for ( int i = 0; i<arr.length; i++ ){  
   System.out.println ( "Value: " + arr[i].toString()) ; 
   }
   }
}
Let us compile and run the above program, this will produce the following result.
Priority queue values are: [5, 6, 6, 64, 9]
Value in array: 
Value: 5
Value: 6
Value: 6
Value: 64
Value: 9 

No comments:

Post a Comment

Codility - Lesson 16 Greedy algorithms - 2. MaxNonoverlappingSegments

Source Link: https://app.codility.com/programmers/lessons/16-greedy_algorithms/max_nonoverlapping_segments/ Question: Located on a line ...