Reputation: 136509
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?
Upvotes: 1
Views: 6295
Reputation: 786329
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*");
Upvotes: 3
Reputation: 90
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]);
}
Upvotes: 1
Reputation: 1300
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.
Upvotes: 1