What is Java priority queue? Introduction to Java Compiler API

PriorityQueue is one of the important Java API unbounded priority queue based on a priority heap and construction. Through the appropriate code sample depth understanding of some of the complex information about the API and its usage. Another in the last article we talked briefly under the Java API Introduction to the compiler , you can read in order to facilitate better read this article. Given help thank You Rui class teacher told me to write these two articles.

 

Overview

PriorityQueue java.util class is part of the package, is the priority queue of the generic Java based. Queue is essentially a data structure that defines a particular specification for the insertion and retrieval of the items in the store. The idea with many people waiting in line, said tickets are very similar. The first person in line had a chance to get the first lottery, the last person to have a chance of ending. It is added to the end or the end of the queue. Add in the queue project is technically called into the team process, removed from the queue project is to start from the first row of the row. This is called a team. The idea is based on FIFO manner sorts the elements.

Now, this is the simplest architecture and tightly defines the actual meaning of the queue and how to simulate the queue in the computer. Generally represented by a simple memory array, wherein the storage and retrieval process specifications have defined herein. On top of this priority queue impose special specifications. We will see more later.

 

Queue Java implementation

Java API have a common interface name Queue <E> in java.util package. This is part of the Java Collection Framework API, designed to save the elements before processing. As part of the collection, which has all the basic set operations. It relates to operation of a particular identifier stored in element inserted therein, extraction and inspection. Each has two different forms of these operations, such as one throw an exception if the operation fails, and the other is an operation of returning a special value such as null or false. Please note that the typical queue differ, it is not necessarily to achieve Java Queue FIFO manner sorts the elements. This is especially true for the priority-based queues, which are sorted according to a comparison element or natural ordering of supplied. But no matter what order, remove () or poll () method will always retrieve the element head of the queue. Specific distinction between these two methods seems unlikely a similar method, i.e., an exception is thrown (NoSuchElementException) on failure, the latter returns a special value (null).

 

method

Throw an exception

description

 

E remove()

NoSuchElementException

Retrieve an element from the head of the queue.

 

void add(E)

IllegalStateException

Insert an element at the end of the queue. Successful return true, if space is not available exception is thrown.

 

E element()

NoSuchElementException

Retrieval element without removing it from the head of the queue.

 

 

 

 

 

 

method

Returns the special value

Explanation

boolean offer(E)

true or false

The elements into the queue. Successful return true, if for lack of space can not be inserted, false is returned.

E poll()

null

Removing an element from the head of the queue; if the queue is empty, null is returned.

E peek()

null

Retrieves, but does not remove elements from the start of the queue. If the queue is empty, null is returned.

           

Note, Queue <E> Interface not available for concurrent programming, because it does not define the blocking queue method, in this method, the process waits for and dequeue the queue element appears in the size or available. There is a BlockingQueue <E> specific interface called the interface extends the Queue <E> Interface and solve these problems.

There called AbstractQueue <E> is an abstract class, which provides some portion of the queue implemented operations. PriorityQueue <E> is a direct extension of this class abstract class.

 

Priority Queue

Java implementation of priority queue is a special queue, which sort the elements by their natural ordering principle determined, it may also be provided in accordance created during Comparator customization. We call the constructor during construction decide to use ordering principle with the priority queue. And Queue <E> not permit null elements of different, but some implementations (e.g. the LinkedList) does not prohibit the insertion of null elements. However, PriorityQueue <E> did not allow empty elements. If the priority queue is constructed according to the natural order, any comparable insertion element will not initiate ClassCastException.

It is declared to be unlimited and based on a priority heap. Although the size of the queue is referred to it is not limited, but internally has the ability to determine the size of the array. When you insert an element, this size will grow automatically. However, there is no principle to increase the size of the detail.

There are seven types of overloaded constructor, we can set the parameters by which to specify the initial capacity of the queue, provided Comparator to specify a custom order of the elements, or the use of no-argument constructor Acceptance all default values.

  • PriorityQueue()
  • PriorityQueue(int initialCapacity)
  • PriorityQueue(int initialCapacity, Comparator<? Super E> comparator)
  • PriorityQueue(Commection<? extends E> c)
  • PriorityQueue(Comparator<? Super E> comparator)
  • PriorityQueue(PriorityQueue<? extends E> c)
  • PriorityQueue(SortedSet<? extends E> c)

And Queue <E> Similarly, PriorityQueue <E> are not synchronized, so caution should be used in concurrent programming. However, there is an alternative method of synchronization, it is referred PriorityBlockingQueue <E>. This PriorityQueue <E> works the same, except with additional qualifiers thread safe.

Operation of Queue <E> PriorityQueue <E> are the same as defined, with some additional features.

method

description

void clear()

Delete all elements from the priority queue.

Comparator<? Super E> comparator()

Returns the comparator associated with the queue. If natural ordering queue, null is returned.

boolean contains(Object o)

If the queue contains the specified object, it returns true.

Iterator<E> iterator()

Returns an iterator associated with the old class Collection. However, it is not guaranteed to traverse the elements in any particular order.

Spliterator<E> spliterator()

Creating late binding, rapid fault splitter, but with the iterator the same conditions.

Object[] toArray()

This is a convenient way, it may be used to set the order of traversal permissions, e.g. Arrays.sort (priorityQueue.toArray ()) .

<T>T[] toArray(T[] a)

It returns the array elements, but the return type is determined by the specified array.

 

Quick Example 1

Let's use a simple program to achieve PriorityQueue <E> of some operations.

 1 package org.mano.examples;
 2 import java.util.Arrays;
 3 import java.util.Iterator;
 4 import java.util.PriorityQueue;
 5 public class Example1 {
 6    public static void main(String[] args){
 7       PriorityQueue<String> pq = new PriorityQueue<>();
 8       pq.add("Mercury");
 9       pq.add("Venus");
10       pq.add("Earth");
11       pq.add("Mars");
12       pq.add("Jupiter");
13       pq.add("Saturn");
14       // Get the most priority element based upon
15       // natural alphabetic ordering in string
16       System.out.println("Priority element "+pq.peek());
17       // Queue elements
18       show(pq);
19       // Remove top of the queue element
20       pq.poll();
21       show(pq);
22       // Retrieves element from the head of the queue
23       pq.remove("Earth");
24       show(pq);
25       String result = pq.contains("Earth")?
26          "Found Earth":"Earth Missing!";
27       System.out.println(result);
28       Object[] arr = pq.toArray();
29       Arrays.sort(arr);
30       System.out.println("");
31       for (int i = 0; i<arr.length; i++)
32          System.out.print(arr[i].toString()+"::");
33    }
34    public static void show(PriorityQueue<String> pq){
35       Iterator<String>Perfume = pq.iterator();
36       while (itr.hasNext())
37          System.out.print(itr.next()+"::");
38          System.out.println("");
39    }
40 }

 

Output

1 Priority element Earth
2 Earth::Jupiter::Mercury::Venus::Mars::Saturn::
3 Jupiter::Mars::Mercury::Venus::Saturn::
4 Jupiter::Mars::Mercury::Venus::Saturn::
5 Earth Missing!
6  
7 Jupiter::Mars::Mercury::Saturn::Venus::

 

Quick Example 2

This is another example of fast comparator with a custom filter.

 1 package org.mano.examples;
 2 import java.util.Comparator;
 3 import java.util.PriorityQueue;
 4 public class Planet implements Comparable<Planet>{
 5    private String name;
 6    private double orbitPeriodInDays;
 7    public Planet(String name, double orbitPeriodInDays) {
 8       this.name = name;
 9       this.orbitPeriodInDays = orbitPeriodInDays;
10    }
11    public String getName() {
12       return name;
13    }
14    public void setName(String name) {
15       this.name = name;
16    }
17    public double getOrbitPeriodInDays() {
18       return orbitPeriodInDays;
19    }
20    public void setOrbitPeriodInDays(double orbitPeriodInDays) {
21       this.orbitPeriodInDays = orbitPeriodInDays;
22    }
23    @Override
24    public int compareTo(Planet o) {
25       return 0;
26    }
27    @Override
28    public String toString() {
29       return "Planet{" +
30          "name='" + name + '\'' +
31          ", orbitPeriodInDays=" + orbitPeriodInDays +
32          '}';
33    }
34    public static void main(String[] args){
35       Comparator<Planet> nameSorter =
36          Comparator.comparing(Planet::getName);
37       PriorityQueue<Planet> priorityQueue = new
38          PriorityQueue<>(nameSorter);
39       priorityQueue.add(new Planet("Mercury",88));
40       priorityQueue.add(new Planet("Venus",225));
41       priorityQueue.add(new Planet("Earth",365.24));
42       priorityQueue.add(new Planet("Mars",693.5));
43       priorityQueue.add(new Planet("Jupiter",4343.5));
44       priorityQueue.add(new Planet("Saturn",10767.5));
45       priorityQueue.add(new Planet("Uranus",30660));
46       priorityQueue.add(new Planet("Neptune",60152));
47       Object[] list = priorityQueue.toArray();
48       for (Object o: list)
49          System.out.println(o);
50    }
51 }

 

Output

1 Planet{name='Earth', orbitPeriodInDays=365.24}
2 Planet{name='Jupiter', orbitPeriodInDays=4343.5}
3 Planet{name='Mercury', orbitPeriodInDays=88.0}
4 Planet{name='Neptune', orbitPeriodInDays=60152.0}
5 Planet{name='Mars', orbitPeriodInDays=693.5}
6 Planet{name='Saturn', orbitPeriodInDays=10767.5}
7 Planet{name='Uranus', orbitPeriodInDays=30660.0}
8 Planet{name='Venus', orbitPeriodInDays=225.0}

 

to sum up

Other priority queue specification is to delete the item from the list with the highest priority. Java will be the priority of the rules imposed on other conventional queue is through additional elements of an ordering principle. The sequence can be customized according to the requirements of the programmer may be set as the default. This is the essence of Java in the priority queue implementation.

Thanks for reading!

Guess you like

Origin www.cnblogs.com/youruike-/p/12054471.html