簡體   English   中英

ClassCastException字符串為Object []

[英]ClassCastException String to Object[]

我正在使用以下代碼:

{
    // ...
    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 []。

嘗試這個:

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

嘗試使用以下方法將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);
    }

你能做到這一點:

Object[] objArr = iter.next();

變成這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM