0

Possible Duplicate:
convert String arraylist to string array in java?

Following is my code

ArrayList<String> IdList = new ArrayList<String>();

and I want to copy items from IDList to int IdArray[].

Community
  • 1
  • 1
Soniya
  • 313
  • 2
  • 5
  • 15

6 Answers6

6

Try this stuff,

     int arr[] = new int[arrList.size()];
        for (int i = 0; i < arrList.size(); i++) {
            arr[i] = Integer.parseInt(arrList.get(i));
        }
Lalit Poptani
  • 66,608
  • 21
  • 157
  • 241
1

String [] outStrArray = (String [])IdList.toArray()

  • 1
    This will throw a ClassCastException because `Collection.toArray()` returns a `Object[]`. – x4u Oct 14 '11 at 09:28
1
ArrayList<String> IdList = new ArrayList<String>();
int IdArray[].
    for (int i = 0; i < IdList.size(); i++) {
        IdArray[i] = (int)IdList.get(i));
    }
warbio
  • 466
  • 5
  • 16
0
int[] IdArray = IdList.toArray(); 

However, this will probably fail because you're trying to convert a string-arraylist to an int-array..

Rob
  • 4,891
  • 12
  • 49
  • 51
0

I think you must iterate through all items, which are Strings, and parse each of them into an int to populate your new int[] array.

styken
  • 74
  • 6
  • Did you mean, Iterator itr = IdList.iterator(); int IdArray[]={}; int d=0; while(itr.hasNext()) { String topic_id = (String) itr.next(); IdArray[d]= Integer.parseInt(topic_id); d++; System.out.print("============"+topic_id ); } – Soniya Oct 14 '11 at 09:11
0
// String array
String[] arr = idList.toArray(new String[0]);
// for int array
int[] iarr = new int[arr.length];
int idx = 0;
for(String s : arr) {
   iarr[idx++] = Integer.parseInt(s);
}
Prince John Wesley
  • 60,780
  • 12
  • 83
  • 92