Java: Copy array of Integers into Array of Strings

arraysintegerjavastring

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?

Best Answer

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*");