ClassCastException: java.lang.Object[] cannot be cast to java.lang.String[] android

后端 未结 5 516
不知归路
不知归路 2020-12-24 10:17

In my application I need to convert my arraylist to a string of an array. However, I am getting an error:

ClassCastException: java.lang.Object[] cannot be ca         


        
相关标签:
5条回答
  • 2020-12-24 10:56

    You should use toArray as mentioned above, but not in that way.

    Either initialize the array first and fill it:

    String[] urlArray = new String[image_urls.size()];
    image_urls.toArray(urlArray);
    

    After which, urlArray will contain all the Strings from image_urls, or pass in a zero-length String array:

    listofurls = (String[]) image_urls.toArray(new String[0]);
    

    See the documentation for toArray().

    0 讨论(0)
  • 2020-12-24 10:58

    You just need to get the contents of arraylist in an array, right??

    Can't u do like this?

           for(int i=0;i<folio.length();++i)
            {
                String m = folio.getString(i);
                Log.v("M"+i,m);
                image_urls.add(m);
                Log("test-url"+image_urls);
    
    
                listofurls[i] = m ;
            }
    
    0 讨论(0)
  • 2020-12-24 11:10

    try

    listofurls = image_urls.toArray(new String[image_urls.size()]);
    

    Note: I suggest to rename listofurls to arrayOfURLs

    0 讨论(0)
  • 2020-12-24 11:18
    listofurls = image_urls.toArray(new String[0]);
    

    that should do the trick for all cases, even if you don't know the size of the resulting array.

    0 讨论(0)
  • 2020-12-24 11:19

    Try this:

    ArrayList<String> stock_list = new ArrayList<String>();
    stock_list.add("stock1");
    stock_list.add("stock2");
    String[] stockArr = new String[stock_list.size()];
    stockArr = stock_list.toArray(stockArr);
    for(String s : stockArr)
        System.out.println(s);
    

    Taken directly from here: link

    0 讨论(0)
提交回复
热议问题