[英]Another way to convert ArrayList containing Strings to an array of Strings in Java?
我已經檢查了以下stackoverflow源以解決我的問題:
但是,在應用最佳解決方案時,仍然出現錯誤,如下所示:
我的清單在這里定義:
List linhaInicial = new ArrayList();
我的轉換是在這里進行的:
String[] convertido = linhaInicial.toArray(new String[linhaInicial.size()]);
問題是我仍然收到以下錯誤:
Error:(86, 59) java: incompatible types
required: java.lang.String[]
found: java.lang.Object[]
我的轉換仍然以某種方式仍返回Object[]
,而現在應該返回String[]
。
有什么辦法嗎?
謝謝!
變更:
List linhaInicial = new ArrayList(); // can contain any Object.
//So compiler throws an error while converting an Object to String.
至
List<String> linhaInicial = new ArrayList<String>(); // using Generics ensures
//that your List can contain only Strings, so, compiler
//will not throw "incompatible types" error
始終嘗試在聲明中包括list元素的類型:
List<String> linhaInicial = new ArrayList<String>();
盡可能避免使用原始類型。
你必須改變
List linhaInicial = new ArrayList(); // you are using raw type List
至
List<String> linhaInicial = new ArrayList();// you have to use String type List
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.