0

I am using the following code:

{
    // ...
    String[] roles = new String[resultList.size()];
    int i=0;
    for (Iterator<Object[]> iter = resultList.iterator(); iter.hasNext();) {
        roles[i] = new String();
        Object[] objArr = iter.next();
        roles[i] = objArr[0].toString();
        i++;
    }
return roles;
}

However, I get a ClassCastException saying cannot cast from java.lang.String to Object[].

11
  • can you provide the stacktrace Commented Aug 6, 2014 at 13:46
  • 1
    String is an Object but all the Objects are not Strings. You can not cast Object to String. Commented Aug 6, 2014 at 13:46
  • which line throws the ClassCastException? Commented Aug 6, 2014 at 13:46
  • 5
    Does it really say "cannot cast from java.lang.String to Object" (this should not be a problem), or "cannot cast from java.lang.String to Object[]"? Commented Aug 6, 2014 at 13:46
  • java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.Object; Line 5 in the code throws Exception Commented Aug 6, 2014 at 13:49

3 Answers 3

1

try this:

{
    // ...
    String[] roles = new String[resultList.size()];
    int i=0;
    for (Iterator<String> iter = resultList.iterator(); iter.hasNext();) {            
        roles[i] = iter.next();
        i++;
    }
    return roles;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try this to convert an Object list to a String array:

    // Create an object list and add some strings to it
    List<Object> objectList = new ArrayList<>();
    objectList.add("A");
    objectList.add("B");
    objectList.add("C");

    // Create an String array with the same size of the object list
    String[] stringArray = new String[objectList.size()];

    // Iterate over the object list to fill the string array, invoking toString() in each object to get a textual representation from it
    for (int i = 0; i < objectList.size(); i++) {
        Object object = objectList.get(i);
        stringArray[i] = object.toString();
    }

    // Iterate over the string array to print the strigs
    for (String string : stringArray) {
        System.out.println(string);
    }

1 Comment

It's a list of String, and he's trying to (implicitly) cast the elements to Object[].
0

Can you make this:

Object[] objArr = iter.next();

Into this:

  String[] objArr = (String[]) iter.next();

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.