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[].

4
  • int[] or String[] array? Commented Oct 14, 2011 at 9:05
  • Actually i want it int array. but String[] is also fine. Commented Oct 14, 2011 at 9:06
  • You should start with an ArrayList<int> in the first place if it doesn't matter XD Commented Oct 14, 2011 at 9:08
  • @ All: Thanks for your help. Following code helped me out String[] array = Idlist.toArray(new String[list.size()]); Commented Oct 14, 2011 at 10:08

6 Answers 6

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));
        }
Sign up to request clarification or add additional context in comments.

3 Comments

gave ArrayIndexOutOfBoundException
int asize= IdList.size(); int arr[] = new int[asize]; for (int i = 0; i < asize); i++) { arr[i] = Integer.parseInt(IdList.get(i)); }
1
ArrayList<String> IdList = new ArrayList<String>();
int IdArray[].
    for (int i = 0; i < IdList.size(); i++) {
        IdArray[i] = (int)IdList.get(i));
    }

Comments

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.

1 Comment

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 ); }
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);
}

Comments

0

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

1 Comment

This will throw a ClassCastException because Collection.toArray() returns a Object[].
-1
int[] IdArray = IdList.toArray(); 

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.