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?

2
  • It's not a problem, but I thought there would be something more elegant, perhaps reminiscent of Python's list comprehension. Commented Feb 27, 2012 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 Commented Feb 27, 2012 at 12:07

3 Answers 3

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*");
Sign up to request clarification or add additional context in comments.

7 Comments

-1 the question is: "I can iterate and convert each element, but is there a more elegant way?"
I gave it a +1, not accepted it. And it might be the right answer if there isn't any one-liner.
so the right answer is something that you already knew isn't it?
The second solution adds extraneous spaces to all string elements with an index greater than 0.
@simon: .split("\\s*,\\s*"); will strip all spaces.
|
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.

Comments

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]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.