CopyOnWriteArrayList คืออะไร?
CopyOnWriteArrayList เป็นคลาสที่ปลอดภัยต่อเธรด (thread-safe) ซึ่งเป็นตัวแปรแบบของ ArrayList โดยการดำเนินการเพิ่ม (add), แก้ไข (set) และอื่นๆ จะสร้างสำเนาใหม่ของอาร์เรย์ที่อยู่เบื้องล่าง ทำให้เหมาะสำหรับสถานการณ์ที่มีการอ่านมากกว่าการเขียน
ตัวอย่างการใช้งาน CopyOnWriteArrayList ใน Android
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่ใน Android Studio
ไปที่ File → New Project และกรอกรายละเอียดที่จำเป็นเพื่อสร้างโปรเจกต์ใหม่
ขั้นตอนที่ 2: เพิ่มโค้ดใน 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>
ในโค้ดข้างต้น เราใช้ TextView เพื่อแสดงองค์ประกอบของ CopyOnWriteArrayList
ขั้นตอนที่ 3: เพิ่มโค้ดใน 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.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);
}
}
การทดสอบแอปพลิเคชัน
เชื่อมต่ออุปกรณ์ Android จริงกับคอมพิวเตอร์ ใน Android Studio เปิดไฟล์กิจกรรมของโปรเจกต์และคลิกไอคอน Run จากแถบเครื่องมือ เลือกอุปกรณ์มือถือของคุณเป็นตัวเลือก และตรวจสอบหน้าจออุปกรณ์ซึ่งจะแสดงหน้าจอเริ่มต้นพร้อมรายการข้อมูล