CopyOnWriteArrayList में set(index, element) - थ्रेड-सेफ अपडेट
set(int index, E element) निर्दिष्ट इंडेक्स पर एलिमेंट को रिप्लेस करता है। पूरी आंतरिक ऐरे की नई कॉपी बनाता है।
चरण 1: प्रोजेक्ट बनाएं
Android Studio: File → New Project।
चरण 2: लेआउट (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:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/actionEvent"
android:textSize="40sp"
android:layout_marginTop="30dp"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</LinearLayout>
चरण 3: MainActivity.java - set() डेमो
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.RequiresApi;
import androidx.appcompat.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("साई");
copyOnWriteArrayList.add("राम");
copyOnWriteArrayList.add("कृष्ण");
copyOnWriteArrayList.add("प्रसाद");
copyOnWriteArrayList.add("राम");
actionEvent.setText("" + copyOnWriteArrayList);
actionEvent.setOnClickListener(v -> {
// इंडेक्स 0 (पहला एलिमेंट) रिप्लेस करें
String old = copyOnWriteArrayList.set(0, "पहला एलिमेंट रिप्लेस्ड");
actionEvent.setText("पुराना: " + old + "\nनया: " + copyOnWriteArrayList);
});
}
}
set() मेथड विवरण:
- रिटर्न: पुराना एलिमेंट जो रिप्लेस हुआ
- थ्रेड-सेफ: एटॉमिक रीड-राइट (कॉपी के साथ)
- एक्सेप्शन: IndexOutOfBoundsException अगर इंडेक्स अमान्य
- कॉम्प्लेक्सिटी: O(n) - पूरी ऐरे कॉपी होती है
सुरक्षित पैटर्न:
int index = 0;
if (index >= 0 && index < list.size()) {
String old = list.set(index, newValue);
} else {
// इंडेक्स आउट ऑफ बाउंड्स हैंडल करें
}
आउटपुट
पहले: [साई, राम, कृष्ण, प्रसाद, राम]
क्लिक के बाद: पुराना: साई\nनया: [पहला एलिमेंट रिप्लेस्ड, राम, कृष्ण, प्रसाद, राम]


चेतावनी: बड़े लिस्ट्स पर बार-बार set() न करें - हर कॉल पर O(n) कॉपी।