0
private ArrayList<Integer> list;
...
...
...
for (int i=0; i < list.size(); i++) {
                Log.e("downloadTask","resource ID is " + list.get(i));
            }
Integer[]  resourceId = resourceId= (Integer[])list.toArray();

before for() statement, list had already been initialized. It has three elements; The Log message is right, but when run

Integer[]  resourceId = (Integer[]) list.toArray();

it will throw Exceptions. I don't know how to solve this problem.

Pshemo
  • 122,468
  • 25
  • 185
  • 269

1 Answers1

1

list.toArray() returns an array of objects (Object[]), which can not be cast to an integer array (because Object[] can contain anything, like String, Boolean, SpiderMan, not only Integer).

Try:

list.toArray(new Integer[list.size()]); //will fill and return passed array 
                                        //with all elements from list

In the future, please provide the exact exceptions being thrown (and include the stack trace) so it's easier for people to spot the problem.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Emile Pels
  • 3,837
  • 1
  • 15
  • 23
  • First ,thank you for your help.But I still don't know “new Integer[list.size()]” meaning. It means creating an new Integer[3] array that copy from list ,yes or no? – Weiguang Meng Mar 01 '15 at 14:45
  • That's correct, what the line `list.toArray(new Integer[list.size()]);` does is creating an array of integers with the list's size as its length, and pass that to the `toArray` method to fill. See: http://docs.oracle.com/javase/7/docs/api/java/util/List.html#toArray%28T[]%29 – Emile Pels Mar 01 '15 at 14:50
  • I have already know the meaning from "http://stackoverflow.com/questions/5374311/convert-arrayliststring-to-string". Thank you again. – Weiguang Meng Mar 01 '15 at 14:53