CopyOnWriteArrayList में get(index) मेथड का उपयोग
CopyOnWriteArrayList थ्रेड-सेफ लिस्ट है जहां get(index) O(1) समय में एलिमेंट एक्सेस देता है - स्नैपशॉट इटेरेटर के साथ।
चरण 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 - get(index) डेमो
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);
// क्लिक पर इंडेक्स 1 का एलिमेंट प्राप्त करें
actionEvent.setOnClickListener(v -> {
try {
String element = copyOnWriteArrayList.get(1); // दूसरा एलिमेंट
actionEvent.setText("इंडेक्स 1: " + element);
} catch (IndexOutOfBoundsException e) {
actionEvent.setText("अमान्य इंडेक्स");
}
});
}
}
CopyOnWriteArrayList की विशेषताएं:
- स्नैपशॉट इटेरेटर: इटेरेशन के दौरान लिस्ट बदलने पर ConcurrentModificationException नहीं।
- रीड-हेवी के लिए: पढ़ना तेज (लॉक-फ्री), लिखना धीमा (पूरी कॉपी)।
- null अनुमत: ArrayList की तरह null एलिमेंट्स अनुमत।
मुख्य मेथड्स:
| मेथड | विवरण |
|---|---|
get(index) | इंडेक्स पर एलिमेंट (O(1)) |
set(index, element) | इंडेक्स पर रिप्लेस (कॉपी बनाता है) |
add(index, element) | इंडेक्स पर इन्सर्ट (कॉपी बनाता है) |
remove(index) | इंडेक्स से हटाएं (कॉपी बनाता है) |
आउटपुट
प्रारंभ: [साई, राम, कृष्ण, प्रसाद, राम]
क्लिक के बाद: इंडेक्स 1: राम


चेतावनी: बड़े लिस्ट्स पर बार-बार लिखने (add/set/remove) से बचें - हर ऑपरेशन पर पूरी ऐरे कॉपी होती है।