1

Consider a method whose signature contains an Integer Array:

public static void parse(Integer[] categories)

parse needs to call a different method, which expects an Array of Strings. So I need to convert Integer[] to String[].

For example, [31, 244] ⇒ ["31", "244"].

I've tried Arrays.copyOf described here:

String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);

But got an ArrayStoreException.

I can iterate and convert each element, but is there a more elegant way?

Community
  • 1
  • 1
Adam Matan
  • 128,757
  • 147
  • 397
  • 562
  • It's not a problem, but I thought there would be something more elegant, perhaps reminiscent of Python's list comprehension. – Adam Matan Feb 27 '12 at 12:02
  • either way the bottom line is that java has to convert each element separately, so any way you can find may just look nicer, but executes a loop – Hachi Feb 27 '12 at 12:07

3 Answers3

3

If you're not trying to avoid a loop then you can simply do:

String[] strarr = new String[categories.length];
for (int i=0; i<categories.length; i++)
     strarr[i] = categories[i] != null ? categories[i].toString() : null;

EDIT: I admit this is a hack but it works without iterating the original Integer array:

String[] strarr = Arrays.toString(categories).replaceAll("[\\[\\]]", "").split("\\s*,\\s*");
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

You could do it manually by iterating over the Int-Array and saving each element into the String-Array with a .toString() attached:

for(i = 0; i < intArray.length(); i++) {
    stringArray[i] = intArray[i].toString()
}

(Untested, but something like this should be the thing you are looking for)

Hmmm, just read your comment. I don't know any easier or more elegant way to do this, sorry.

malexmave
  • 1,283
  • 2
  • 17
  • 37
1

i don't think that theres a method for it:

use a loop for it like:

String strings[] = new String[integerarray.length];

for(int i = 0; i<integerarray.length;++i)
{
     strings[i] = Integer.toString(integerarray[i]);
}
fnobbi
  • 90
  • 5