search
HomeJavajavaTutorialPriorityQueue priority queue of Java collection framework

This article brings you relevant knowledge about java, which mainly introduces the relevant knowledge about PriorityQueue priority queue. The Java collection framework provides two types of priorities, PriorityQueue and PriorityBlockingQueue. Level queue, PriorityQueue is thread-unsafe, and PriorityBlockingQueue is thread-safe. Let’s take a look at it together. I hope it will be helpful to everyone.

PriorityQueue priority queue of Java collection framework

Recommended study: "java Video Tutorial"

The Java collection framework provides two types of PriorityQueue and PriorityBlockingQueue The priority queue, PriorityQueue is thread-unsafe, and PriorityBlockingQueue is thread-safe. This article mainly introduces PriorityQueue

The relationship of priorityQueue in the Java collection framework is as follows:

1. Points to note when using PriorityQueue

1. When using it, you must import the package where PriorityQueue is located, that is:

import java. util.PriorityQueue

2. The elements placed in the PriorityQueue must be able to be compared in size, and objects that cannot be compared in size cannot be inserted, otherwise
ClassCastException## will be thrown.

#3. Null objects cannot be inserted, otherwise NullPointerException will be thrown

4. There is no capacity limit, you can insert any number of elements, and the internal capacity can be automatically expanded

5 . The

time complexity of inserting and deleting elements is log base 2 n

6. The bottom layer of PriorityQueue uses a heap data structure

7. PriorityQueue by default It is a small heap---that is, the elements obtained every time are the smallest elements (

If we want to turn it into a large heap, we need to re-compare the method. The default comparison method is the compareTo method in the Comparable interface)

2. Introduction to Common Interfaces of PriorityQueue

1. Construction of Priority Queue

Here are just a few common construction methods in

PriorityQueue, for others, you can refer to the help documentation.

ConstructorFunction introductionPriorityQueue()Create an empty Priority queue, PriorityQueue(intCreate a PriorityQueue(CollectionUse a collection to create a priority queue with Create a

2. Comparison of elements in PriorityQueue

After reading the construction method, let’s think about a question again

How does the priority queue achieve order? Because the priority queue is implemented with the help of a small root heap

In the process of implementing the small root heap, we know that a comparison of elements must occur, so the elements in the PriorityQueue must be able to compare in size. So how does PriorityQueue compare elements?

PriorityQueue adopts two methods:
Comparble and Comparator.

1. Comparble is the default internal comparison method . If the user inserts a custom type object, the object must implement the Comparble interface and override compareTo Method

2. Users can also choose to use a comparator object. If the user inserts a custom type object, a comparator class must be provided, and the class must implement the Comparator interface and override it. compare method.

We see that the program reports an error here, why? Because the Child object we inserted is not comparable ( does not implement the Comparable interface and does not use a custom comparator)

You can see

That is, we use the compareTo method in the Comparable interface, which is the default comparison method

At this time, let’s take a look at the error again Information

It seems that there is a problem when inserting elements into PriorityQueue

Then let’s open the source code of PriorityQueue and take a look (The following is the source code of the offer method in PriorityQueue)

Look at the source code of shiftUp again

Continue Click in siftUpComparable

At this time, let’s look back at the Child object we put in the PriorityQueue. It has no custom comparator and does not implement the Comparable interface. ,Of course an error is reported!

Okay then, let’s implement the Comparable interface in the Child class and compare by age

import java.util.PriorityQueue;
class Child implements Comparable<child>{
    int age;
    String name;

    public Child(int age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public int compareTo(Child o) {
        return this.age - o.age;  // 默认实现小根堆
    }

    @Override
    public String toString() {
        return "Child{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}
public class TestPriorityQueue {
    public static void main(String[] args) {
        PriorityQueue<child> priorityQueue = new PriorityQueue();

        priorityQueue.offer(new Child(12, "小亮"));
        priorityQueue.offer(new Child(11, "小红"));
        priorityQueue.offer(new Child(8, "小强"));
        System.out.println(priorityQueue);
    }
}</child></child>

If you want to implement a large root heap, It’s easy to do

# Above we have implemented the Compable interface, so what if we customize an age comparator?

class Child {
    int age;
    String name;

    public Child(int age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Child{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}
class AgeComparator implements Comparator<child> {

    @Override
    public int compare(Child o1, Child o2) {
        return o1.age - o2.age; // 实现小根堆
        // return o2.ae - o1.age 实现大根堆
    }
}
public class TestPriorityQueue {
    public static void main(String[] args) {
        AgeComparator ageComparator = new AgeComparator();
        // 创建具有默认初始容量的 PriorityQueue ,并根据指定的比较器对其元素进行排序。
        PriorityQueue<child> priorityQueue = new PriorityQueue(ageComparator);
        // 可以看到这里我的Child对象虽然没有实现Comparable接口,但因为我们对Child对象自定义了一个年龄比较器,所以插入元素不会报错
        priorityQueue.offer(new Child(12, "小亮"));
        priorityQueue.offer(new Child(11, "小红"));
        priorityQueue.offer(new Child(8, "小强"));
        System.out.println(priorityQueue);
    }
}</child></child>

3. Insert/delete/get the highest priority element

The default capacity is 11
initialCapacity)
initial capacity is initialCapacity Priority queue, Note: initialCapacity cannot be less than 1, otherwise an IllegalArgumentException will be thrown Often
extends E> c)
##PriorityQueue(Comparator super E> comparator)Create a priority queue default initial capacity and compare its elements against the specified comparator
PriorityQueue(int initialCapacity, Comparator super E> comparator) Initial capacity is

initialCapacity's priority queue<strong></strong>, compares its elements according to the specified comparator

Note:

initialCapacity cannot be less than 1, otherwise IllegalArgumentException will be thrown Often

E peek()Get the element with the highest priority , if the priority queue is empty, return nullE poll()Remove the highest priority element and return, if the priority queue is empty, return nullint size()Get the number of valid elementsvoidClearCheck whether the priority queue is empty and return if empty true
Function Name Function introduction
boolean
offer(E e)
Insert element e, and return true if the insertion is successful, if the e object is empty , throwing NullPointerException, time complexity, note: when the space is not enough, it will be expanded
clear()
boolean

isEmty()

Recommended learning: "

java video tutorial"

The above is the detailed content of PriorityQueue priority queue of Java collection framework. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Is Java Platform Independent if then how?Is Java Platform Independent if then how?May 09, 2025 am 12:11 AM

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

The Truth About Java's Platform Independence: Is It Really That Simple?The Truth About Java's Platform Independence: Is It Really That Simple?May 09, 2025 am 12:10 AM

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java Platform Independence: Advantages for web applicationsJava Platform Independence: Advantages for web applicationsMay 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM Explained: A Comprehensive Guide to the Java Virtual MachineJVM Explained: A Comprehensive Guide to the Java Virtual MachineMay 09, 2025 am 12:04 AM

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Key Features of Java: Why It Remains a Top Programming LanguageKey Features of Java: Why It Remains a Top Programming LanguageMay 09, 2025 am 12:04 AM

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft