Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách dùng peek() trong ConcurrentLinkedQueue Android

peek() - Xem phần tử đầu hàng đợi

peek() trên ConcurrentLinkedQueue trả về phần tử ở đầu (head) theo FIFO không xóa nó. Trả về null nếu queue rỗng. An toàn luồng, non-blocking.

Lưu ý về code gốc

Code mẫu gốc có lỗi: bên trong onClick lại gọi isEmpty() thay vì peek(). Dưới đây là code đã sửa.

MainActivity.java (Đã sửa)

package com.example.myapplication;

import android.os.Build;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.TextView;
import java.util.concurrent.ConcurrentLinkedQueue;

public class MainActivity extends AppCompatActivity {

    private ConcurrentLinkedQueue<String> concurrentLinkedQueue;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        concurrentLinkedQueue = new ConcurrentLinkedQueue<>();
        final TextView actionEvent = findViewById(R.id.actionEvent);

        concurrentLinkedQueue.add("sai");
        concurrentLinkedQueue.add("ram");
        concurrentLinkedQueue.add("krishna");
        concurrentLinkedQueue.add("prasad");
        concurrentLinkedQueue.add("ram");

        actionEvent.setText("Queue: " + concurrentLinkedQueue);

        actionEvent.setOnClickListener(v -> {
            // SỬA: Dùng peek() thay vì isEmpty()
            String head = concurrentLinkedQueue.peek();
            actionEvent.setText("peek(): " + head); // "sai"
        });
    }
}

So sánh peek() vs poll()

  • peek(): Chỉ xem, giữ nguyên queue. Trả null nếu rỗng.
  • poll(): Lấy và xóa phần tử đầu. Trả null nếu rỗng.