1

I don't understand why this is giving me a class cast exception:

List<String> names = new ArrayList<String>();
for (ApplicationInfo app : apps) {
    names.add("" + app.loadLabel(packageManager));
}
return (String[]) names.toArray();

the log is:

01-23 16:56:18.746: E/AndroidRuntime(4027): Caused by: java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.String[]

but I clearly defined names to be a list of String and not Object

**EDIT:

oh wait, okay i see in the API it returns array of objects. how could i do this without doing:

List<String> names = new ArrayList<String>();
for (ApplicationInfo app : apps) {
    names.add("" + app.loadLabel(packageManager));
}
String[] list = new String[names.size()];
return names.toArray(list);

and making a new array each time?

David T.
  • 22,301
  • 23
  • 71
  • 123

5 Answers5

4

Based on the javadoc, you can do this:

String[] list = names.toArray(new String[0]);
aysonje
  • 2,595
  • 1
  • 14
  • 16
3

The class cast exception happened just because toArray() returns Object[]. Surely Object[] cannot cast to String[].

Insteadly, you can use this:

String[] list = toArray(new String[names.size()]);

which returns the right cast(String[]).

sun
  • 66
  • 4
1

You just have to, either by you directly, or indirectly. Someone got to create a array (with correct size) to hold the result.

new String[0] is for dummy, but you will create two objects.

If you believe an additional array object do matter, you should REUSE the String[] object, or just use the List without convert to array.

Dennis C
  • 24,511
  • 12
  • 71
  • 99
  • Over 10k rep and you post an answer rather than mark as a dup? If this answer was better or more complete than the duplicate then that would fly but this... – Boris the Spider Jan 24 '14 at 01:11
1

You are working on generics and at run time it is not able to identify what type of array to create and what is the size to be allocated to that array.

A very simple working solution.

ApplicationInfo a1  = new ApplicationInfo("label1");
    ApplicationInfo a2  = new ApplicationInfo("label2");
    ApplicationInfo a3  = new ApplicationInfo("label3");

    List<ApplicationInfo> infos = new ArrayList<ApplicationInfo>();
    infos.add(a1);
    infos.add(a2);
    infos.add(a3);

    ArrayList<String> labels = new ArrayList<String>();
    for (ApplicationInfo info : infos) {
        labels.add(info.getLabel().toString());
    }

    String[] lbls = labels.toArray(new String[labels.size()]);
    for (int i = 0; i < lbls.length; i++) {
        System.out.println(lbls[i]);
    }
NarendraSoni
  • 2,210
  • 18
  • 26
0

You could do this instead:

String[] list = new String[0];
return names.toArray(list);

You don't need to allocate the additional space for the size of your array.

Dana
  • 490
  • 1
  • 4
  • 11