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?

share|improve this question

2  
Any problem with for loop? – Harry Joy Feb 27 '12 at 12:00
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
feedback

3 Answers

up vote 3 down vote accepted

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(",");
share|improve this answer
+1 for avoiding the NullPointerException – Adam Matan Feb 27 '12 at 12:05
1  
-1 the question is: "I can iterate and convert each element, but is there a more elegant way?" – Massimiliano Peluso Feb 27 '12 at 12:10
I gave it a +1, not accepted it. And it might be the right answer if there isn't any one-liner. – Adam Matan Feb 27 '12 at 12:13
so the right answer is something that you already knew isn't it? – Massimiliano Peluso Feb 27 '12 at 12:24
@MassimilianoPeluso: Pls check the EDIT section. Not sure about the elegance but it avoids the iteration of the original array. – anubhava Feb 27 '12 at 14:01
show 1 more comment
feedback

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.

share|improve this answer
feedback

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]);
}
share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.