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

Cách lấy phần tử theo chỉ số trong CopyOnWriteArrayList Android

Giới thiệu về CopyOnWriteArrayList

CopyOnWriteArrayList là list thread-safe, biến thể của ArrayList. Mỗi thao tác ghi (add, set, remove) tạo bản sao mảng mới. Iterator không ném ConcurrentModificationException và hoạt động trên snapshot. Phù hợp cho đọc nhiều, ghi í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);

        // Thêm phần tử mẫu
        copyOnWriteArrayList.add("sai");
        copyOnWriteArrayList.add("ram");
        copyOnWriteArrayList.add("krishna");
        copyOnWriteArrayList.add("prasad");
        copyOnWriteArrayList.add("ram"); // Cho phép trùng lặp

        actionEvent.setText(copyOnWriteArrayList.toString());

        actionEvent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Lấy phần tử tại chỉ số 1 (phần tử thứ 2)
                if (copyOnWriteArrayList.size() > 1) {
                    String element = copyOnWriteArrayList.get(1);
                    actionEvent.setText("Index 1: " + element);
                } else {
                    actionEvent.setText("Danh sách không đủ phần tử");
                }
            }
        });
    }
}

Chạy ứng dụng

Kết nối thiết bị (API 21+) và chạy ứng dụng.

Cách lấy phần tử theo chỉ số trong CopyOnWriteArrayList Android

Nhấn vào TextView để lấy phần tử index 1:

Cách lấy phần tử theo chỉ số trong CopyOnWriteArrayList Android

Đặc điểm truy cập chỉ số:
  • get(index) - O(1) như ArrayList bình thường
  • An toàn cho đa luồng: nhiều luồng đọc đồng thời không vấn đề
  • Iterator trả về snapshot tại thời điểm tạo → không thấy thay đổi sau đó
  • Kiểm tra size() trước khi get() để tránh IndexOutOfBoundsException
  • Phương thức set(index, element) thay thế phần tử tại chỉ số