LinkedList poll() trong java với ví dụ cụ thể

LinkedList poll() trong java trả về phần tử đầu tiên và xoá nó ra khởi LinkedList.

Syntax

public E poll();

Ví dụ

import java.util.LinkedList;

public class Main {
    public static void main(String args[]) {
        LinkedList<String> linkedList = new LinkedList<>();
        linkedList.add("HCMUS");
        linkedList.add("UIT");
        linkedList.add("HCMUT");

        System.out.println("LinkedList ban dau: " + linkedList);
        System.out.println("Phan tu dau tien: " + linkedList.poll());
        System.out.println("LinkedList sau khi poll(): " + linkedList);

    }
}

Output: 

LinkedList ban dau: [HCMUS, UIT, HCMUT]
Phan tu dau tien: HCMUS
LinkedList sau khi poll(): [UIT, HCMUT]

Note: Nếu LinkedList rỗng poll() sẽ trả về null.

 

import java.util.LinkedList;

public class Main {
    public static void main(String args[]) {
        LinkedList<String> linkedList = new LinkedList<>();
        System.out.println("Phan tu dau tien: " + linkedList.poll());

    }
}

Output: Phan tu dau tien: null

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