บทนำ
CopyOnWriteArrayList เป็น List แบบ Thread-safe ตัวอย่างนี้สาธิตการใช้ set(int index, E element) อัปเดตข้อมูลที่ตำแหน่งเฉพาะ
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio เลือก File → New Project กรอกข้อมูลที่จำเป็น
ขั้นตอนที่ 2: ออกแบบ Layout (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:id="@+id/actionEvent"
android:textSize="40sp"
android:layout_marginTop="30dp"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</LinearLayout>
ขั้นตอนที่ 3: เขียนโค้ด Java (src/MainActivity.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.CopyOnWriteArrayList;
public class MainActivity extends AppCompatActivity {
CopyOnWriteArrayList<String> copyOnWriteArrayList;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
copyOnWriteArrayList = new CopyOnWriteArrayList<>();
final TextView actionEvent = findViewById(R.id.actionEvent);
// เพิ่มข้อมูลตัวอย่าง
copyOnWriteArrayList.add("sai");
copyOnWriteArrayList.add("ram");
copyOnWriteArrayList.add("krishna");
copyOnWriteArrayList.add("prasad");
copyOnWriteArrayList.add("ram");
actionEvent.setText("" + copyOnWriteArrayList);
// คลิกเพื่ออัปเดต Index 0 (ตัวแรก)
actionEvent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// set(index, element) แทนที่ข้อมูลเดิม คืนค่าของเก่า
String old = copyOnWriteArrayList.set(0, "replace first element");
actionEvent.setText("Replaced: " + old + "\n" + copyOnWriteArrayList);
}
});
}
}
การทดสอบแอปพลิเคชัน
รันแอปบนอุปกรณ์จริง

คลิก TextView จะแทนที่ Index 0 ("sai") ด้วย "replace first element"

คำอธิบาย set(int index, E element)
- แทนที่องค์ประกอบที่
indexด้วยelementใหม่ - คืนค่าองค์ประกอบ **เก่า** ที่ถูกแทนที่
- Thread-safe: Atomic replace (Copy array ใหม่)
- โยน
IndexOutOfBoundsExceptionหาก Index ไม่ถูกต้อง - Complexity: O(n) เนื่องจาก Copy Array ทั้งหมด
Iterator และ Snapshot Behavior
// Iterator เป็น Snapshot - ไม่เห็นการเปลี่ยนแปลงหลังสร้าง
for (String s : copyOnWriteArrayList) {
// แม้ Thread อื่นจะ set() แล้ว Iterator นี้ก็ยังเห็นค่าเก่า
}
สรุป
ใช้ set(index, element) อัปเดตข้อมูลตาม Index ใน CopyOnWriteArrayList แบบ Thread-safe คืนค่าของเก่า เหมาะสำหรับ Read-heavy Workloads