ConcurrentLinkedQueue को toArray() से ऐरे में बदलना
toArray() क्यू के सभी एलिमेंट्स को एक नए ऐरे में कॉपी करता है। थ्रेड-सेफ स्नैशॉट के लिए उपयोगी।
चरण 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 - toArray() डेमो
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.ConcurrentLinkedQueue;
public class MainActivity extends AppCompatActivity {
ConcurrentLinkedQueue<String> concurrentLinkedQueue;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
concurrentLinkedQueue = new ConcurrentLinkedQueue<>();
final TextView actionEvent = findViewById(R.id.actionEvent);
concurrentLinkedQueue.add("साई");
concurrentLinkedQueue.add("राम");
concurrentLinkedQueue.add("कृष्ण");
concurrentLinkedQueue.add("प्रसाद");
concurrentLinkedQueue.add("राम");
actionEvent.setText("" + concurrentLinkedQueue);
actionEvent.setOnClickListener(v -> {
// Object[] ऐरे में कन्वर्ट
Object[] array = concurrentLinkedQueue.toArray();
// टाइप्ड ऐरे (अनुशंसित)
String[] stringArray = concurrentLinkedQueue.toArray(new String[0]);
StringBuilder sb = new StringBuilder("ऐरे: [");
for (int i = 0; i < stringArray.length; i++) {
sb.append(stringArray[i]);
if (i < stringArray.length - 1) sb.append(", ");
}
sb.append("]");
actionEvent.setText(sb.toString());
});
}
}
toArray() वेरिएंट्स:
| मेथड | रिटर्न टाइप | विवरण |
|---|---|---|
toArray() | Object[] | कास्टिंग जरूरी |
toArray(T[] a) | T[] | टाइप-सेफ, खाली ऐरे पास करें new String[0] |
क्यों new String[0]?
// JVM इंटरनली सही साइज का ऐरे बनाता है // zero-length ऐरे पास करना परफॉर्मेंस के लिए अच्छा (शेयर्ड कंस्टेंट) String[] arr = queue.toArray(new String[0]);
थ्रेड-सेफ्टी नोट:
toArray() क्यू का स्नैपशॉट लेता है - कन्वर्जन के दौरान क्यू मॉडिफाई होने पर भी ऐरे कंसिस्टेंट रहता है।
आउटपुट
प्रारंभ: [साई, राम, कृष्ण, प्रसाद, राम]
क्लिक के बाद: ऐरे में वही एलिमेंट्स

उपयोग केस: लिगेसी API को ऐरे पास करना, स्नैपशॉट लेना, कलेक्शन को ऐरे-आधारित API में भेजना।