Java Priority queue

Source: Internet
Author: User

As the Java API says:

Java.util.PriorityQueue.PriorityQueue ()

Creates a with the PriorityQueue default initial capacity (one) that orders their elements according to their natural ordering.

The default ordering of priority queue Priorityqueue is the natural order of the elements. Take advantage of this feature and use it as a small top pile to find the first k elements in the array.

 Packagestructure;ImportJava.util.Iterator;ImportJava.util.PriorityQueue;ImportJava.util.Queue;/*** Priority Queue usage in Java *@authorDreamy **/ Public classPriorityqueuedemo {/**     * @paramargs*/     Public Static voidMain (string[] args) {//Priorityqueue in Java is sorted by default in natural order        int[] numbers = {4,5,2,1,9,6,8,7};    FINDTOPK (numbers); }    //find the top K large in the array    Private Static voidFINDTOPK (int[] numbers) {Queue<Integer> queue =NewPriorityqueue<integer>(); Final intK = 3;  for(inti=0;i<k;i++) Queue.add (Numbers[i]);  for(inti=k;i<numbers.length;i++){            intMin =Queue.peek (); if(numbers[i]>min)                {Queue.poll ();            Queue.offer (Numbers[i]); }} Iterator<Integer> ITR =Queue.iterator ();  while(Itr.hasnext ()) {intnum =Itr.next ();        SYSTEM.OUT.PRINTLN (num); }    }}

Of course, Priorityqueue can also store custom objects, allowing element objects to implement comparable excuses, overriding CompareTo methods to implement custom sorting. Alternatively, you can also construct a priorityqueue, specifying a custom comparer comparator (as a parameter).

In addition Priorityqueue is non-thread-safe, if you want to consider the synchronization problem under multithreading, you can use the Priorityblockingqueue under the concurrent package.

Java Priority queue

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.