ClassCastException字符串到Object []

时间:2014-08-06 13:36:36

标签: java classcastexception

我使用以下代码:

{
    // ...
    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;
}

但是,我得到一个ClassCastException说不能从java.lang.String转换为Object []。

3 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 1 :(得分:0)

尝试将Object列表转换为String数组:

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

答案 2 :(得分:0)

你能做到这一点:

Object[] objArr = iter.next();

进入这个:

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