3

Possible Duplicate:
How to convert object array to string array in Java

I am receiving an Object and casting it into a String array like this:

Object values[] = (Object[])request.getSession().getAttribute("userList");
String[] tmp = new String[values.length];
for(int i = 0; i < tmp.length; ++i) {
     tmp[i] = (String) values[i];
     out.println(tmp[i]);
}

Is there any better and cleaner way to do this?

2
  • 2
    when you call setAttribute() if you are passing a String[], you can just cast directly to that instead of using an object array as a proxy Commented Jan 9, 2013 at 20:09
  • @TritonMan - That should be an answer. Commented Jan 9, 2013 at 20:15

1 Answer 1

7

Why not directly casting?

String values[] = (String[])request.getSession().getAttribute("userList");
Sign up to request clarification or add additional context in comments.

5 Comments

Why not? Because java.lang.ClassCastException perhaps? Try String[] arr = (String[])(new Object[]{"a", "b", "c"});
@RichardJPLeGuen if getAttribute() is returning Object[] why do you still cast it to Object[] ?
Of note: Object arr = (Object)(new Object[]{"a", "b", "c"}); does not throw an exception.
@RichardJPLeGuen but our concern is Object[] x = (Object[]) obj;, and your example is non-sense.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.