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
  • 311
  • 3
  • 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
  • 67,150
  • 23
  • 161
  • 242
  • gave ArrayIndexOutOfBoundException – Soniya Oct 14 '11 at 09:40
  • int asize= IdList.size(); int arr[] = new int[asize]; for (int i = 0; i < asize); i++) { arr[i] = Integer.parseInt(IdList.get(i)); } – Soniya Oct 14 '11 at 10:00
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/4261/discussion-between-soniya-and-lalit-poptani) – Soniya Oct 14 '11 at 10:43
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

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
  • 62,492
  • 12
  • 87
  • 94
0

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
int[] IdArray = IdList.toArray(); 

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

Rob
  • 4,927
  • 12
  • 49
  • 54