1

I want to convert an ArrayList<Integer> that was put into the args bundle of a fragment to type Integer[] so I can pass it to a method that requires the type Integer[]. I have

ArrayList<Integer> friends

I then created an empty Integer Array.

Integer[] bal= new Integer[friends.size()];

I know I have to do something with the for loop!!

Hana Bzh
  • 2,212
  • 3
  • 18
  • 38
flutter
  • 6,188
  • 9
  • 45
  • 78
  • Something like this? http://stackoverflow.com/questions/718554/how-to-convert-an-arraylist-containing-integers-to-primitive-int-array – Robb Jul 02 '15 at 15:49

2 Answers2

2

In order to fill the array with the values from your array list you can use a loop (like the 'for loop' you mentioned) to iterate through the ArrayList and place its data into the array.

You can use the following code to accomplish this:

Integer[] bal = new Integer[friends.size()];
for(int i=0; i < friends.size(); i++){
  bal[i] = friends.get(i);
}

Let me know if this is all you need, or if you have any other issues!

EDIT: As mentioned in another answer below, you don't have to create a new array and manually fill it with the values from the ArrayList. You could use the toArray() method on the ArrayList class to convert the ArrayList into an array as follows: Integer[] bal = friends.toArray(new Integer[friends.size()]);

ryguy
  • 481
  • 2
  • 7
1

If you want to simply convert ArrayList to Array you can do it as :-

Integer[] bal = friends.toArray(new Integer[friends.size()]);

AnkeyNigam
  • 2,810
  • 4
  • 15
  • 23