ภาพรวมของ ConcurrentLinkedDeque
ConcurrentLinkedDeque เป็น Deque แบบไม่มีขอบเขต (unbounded) บนโหนดเชื่อมโยง รองรับหลายเธรด (thread-safe) อย่างปลอดภัย
ตัวอย่างการใช้งาน pop()
ตัวอย่างนี้สาธิตเมธอด pop() ซึ่งนำสมาชิกที่ หัว (head/front) ออกและคืนค่า ทำงานเหมือน Stack (LIFO) โยน NoSuchElementException หาก Deque ว่าง
ขั้นตอนที่ 1-2: สร้างโปรเจกต์และ Layout
สร้างโปรเจกต์ใหม่ ใช้ Layout TextView เดียวกัน
ขั้นตอนที่ 3: โค้ด Java (แก้ไขข้อผิดพลาด)
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import java.util.concurrent.ConcurrentLinkedDeque;
public class MainActivity extends AppCompatActivity { // แก้: MainActivityextends → MainActivity extends
ConcurrentLinkedDeque<String> concurrentLinkedDeque;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
concurrentLinkedDeque = new ConcurrentLinkedDeque<>();
final TextView actionEvent = findViewById(R.id.actionEvent); // แก้: TextViewactionEvent
concurrentLinkedDeque.add("sai");
concurrentLinkedDeque.add("ram");
concurrentLinkedDeque.add("krishna");
concurrentLinkedDeque.add("prasad");
actionEvent.setText("" + concurrentLinkedDeque);
actionEvent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
concurrentLinkedDeque.pop(); // นำออกที่หัว
actionEvent.setText("" + concurrentLinkedDeque);
}
});
}
}
🔧 การแก้ไขจากโค้ดต้นฉบับ
MainActivityextends→MainActivity extendsTextViewactionEvent→TextView actionEvent- เพิ่ม Generic Type
<String>
pop() vs removeFirst() vs pollFirst()
| เมธอด | พฤติกรรมเมื่อ Deque ว่าง | คืนค่า |
|---|---|---|
pop() | โยน NoSuchElementException | E (element) |
removeFirst() | โยน NoSuchElementException | E |
pollFirst() | คืน null | E |
⚠️ ข้อควรระวัง
pop()โยน Exception หาก Deque ว่าง ต้องใช้try-catchหรือตรวจสอบisEmpty()ก่อน- ใน Production ควรใช้
pollFirst()ที่คืน null แทน (ปลอดภัยกว่า) - ConcurrentLinkedDeque เป็น unbounded จึงไม่มีปัญหาเรื่องความจุ
วิธีทดสอบ
- รันแอป ดูรายการ: [sai, ram, krishna, prasad]
- คลิก TextView เรียก pop() → นำ "sai" ออก เหลือ [ram, krishna, prasad]
- คลิกซ้ำจน Deque ว่าง → จะเกิด Crash (NoSuchElementException)
- ลองแก้โค้ดใช้
pollFirst()แทน จะไม่ Crash คืน null แทน
แนวทางปลอดภัย
// แบบปลอดภัย - ใช้ pollFirst()
String removed = concurrentLinkedDeque.pollFirst();
if (removed != null) {
// ประมวลผล removed
actionEvent.setText("Removed: " + removed + " | Remaining: " + concurrentLinkedDeque);
} else {
actionEvent.setText("Deque is empty!");
}