PriorityQueue peek() trong java với ví dụ cụ thể

PriorityQueue peek() trong java trả về phần tử đầu tiên của PriorityQueue, nếu PriorityQueue rỗng thì nó sẽ trả về null. 

Syntax

import java.util.*;
public class Main {

    public static void main(String[] args) {

        PriorityQueue<Integer> q = new PriorityQueue<>();

        //Adding elements to the Queue
        q.add(1);
        q.add(100);
        q.add(99);
        q.add(46);
        q.add(90);
        System.out.println("Head element: " + q.peek());
    }
}

Output: Head element: 1

Nếu PriorityQueue rỗng thì peek() trả về null

import java.util.*;
public class Main {

    public static void main(String[] args) {

        PriorityQueue<Integer> q = new PriorityQueue<>();
        System.out.println("Head element: " + q.peek());
    }
}

Output: Head element: null

Các bài viết liên quan

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x