Giới thiệu về CopyOnWriteArrayList
CopyOnWriteArrayList là list thread-safe, copy-on-write. Phương thức set(int index, E element) thay thế phần tử tại chỉ số cụ định. Tạo bản sao mảng mới, thay thế phần tử, sau đó swap reference nguyên tử.
Bước 1: Tạo dự án mới
Mở Android Studio, chọn File → New Project, điền thông tin cần thiết.
Bước 2: Thiết kế giao diện (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>
Bước 3: Viết logic (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.toString());
actionEvent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Cập nhật phần tử tại index 0 (phần tử đầu)
if (copyOnWriteArrayList.size() > 0) {
String old = copyOnWriteArrayList.set(0, "thay thế phần tử đầu");
actionEvent.setText("Đã thay: " + old + "\n" + copyOnWriteArrayList.toString());
} else {
actionEvent.setText("List rỗng");
}
}
});
}
}
Chạy ứng dụng
Kết nối thiết bị (API 21+) và chạy ứng dụng.

Nhấn vào TextView để set(0, ...):

Đặc điểm set(index, element):So sánh:
- Thay thế phần tử tại
index, trả về phần tử cũ- Ném
IndexOutOfBoundsExceptionnếu index < 0 hoặc >= size()- Thread-safe: atomic (tạo bản sao mảng, swap reference)
- Iterator đang duyệt KHÔNG thấy thay đổi này (snapshot semantics)
- Hiệu năng: O(n) do copy mảng (n = size)
Phương thức Hành vi Trả về set(index, e)Thay thế tại index Phần tử cũ add(index, e)Chèn tại index, đẩy lui void remove(index)Xóa tại index Phần tử bị xóa