本文介紹了轉(zhuǎn)換列表<字符串>Java中的字符串[]的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
如何轉(zhuǎn)換 列表將字符串轉(zhuǎn)換為 數(shù)組?以下代碼返回錯誤.
How do I convert a list of String into an array? The following code returns an error.
public static void main(String[] args) {
List<String> strlist = new ArrayList<String>();
strlist.add("sdfs1");
strlist.add("sdfs2");
String[] strarray = (String[]) strlist.toArray();
System.out.println(strarray);
}
錯誤:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
at test.main(test.java:10)
推薦答案
你想要的
String[] strarray = strlist.toArray(new String[0]);
參見這里 獲取文檔并注意,您還可以通過填充傳遞的數(shù)組的方式調(diào)用此方法,而不僅僅是使用它來計算要返回的類型.另請注意,當(dāng)您打印數(shù)組時,您可能更喜歡
See here for the documentation and note that you can also call this method in such a way that it populates the passed array, rather than just using it to work out what type to return. Also note that maybe when you print your array you'd prefer
System.out.println(Arrays.toString(strarray));
因為這將打印實際的元素.
since that will print the actual elements.
這篇關(guān)于轉(zhuǎn)換列表<字符串>Java中的字符串[]的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!