[英]How to cast ArrayList<String> to String
這是我的代碼:
ArrayList<String> contentArray = new ArrayList<String>();
for(HashMap<ArrayList<String>, String> subTopicsEntry : subTopics){
contentArray = (ArrayList<String>) subTopicsEntry.get("Content");
}
它給我一個錯誤,就是不能將arraylist強制轉換為java.lang.string。
怎么了
如果我這樣做:
ArrayList<?> contentArray = new ArrayList<?>();
for(HashMap<?, ?> subTopicsEntry : subTopics){
contentArray = (ArrayList<?>) subTopicsEntry.get("Content");
}
有用
有什么區別 ?
首先, Arrays.asList()
返回List<String>
,而不是ArrayList<String>
。
您必須將變量定義為:
List<String> contentArray = new ArrayList<String>();
但這不是您這里遇到的所有問題。
正如評論者指出的那樣,您(可能)錯誤聲明了您的地圖。 也許你是說
ArrayList<String> contentArray = new ArrayList<String>(); // this initializer is unnecessary, btw
for(HashMap<String, ArrayList<String>> subTopicsEntry : subTopics){
contentArray = subTopicsEntry.get("Content"); // Note that a cast is no longer necessary
}
我懷疑您是否真的想要ArrayList
,但是在沒有看到其余代碼的情況下很難說。
我的答案代碼是:
package Examples;
import java.util.ArrayList;
import java.util.List;
public class ExampleClass
{
private List<String> _list;
@Override
public String toString() // override default method
{
String temp = "";
for (String s : this._list)
{
temp += (temp.length() == 0 ? "" : ", ") + s;
}
return "ExampleClass: [" + temp + "]";
}
public ExampleClass() // initialize this example class
{
this._list = new ArrayList<>();
this._list.add("Hello!");
this._list.add("Ciao!");
this._list.add("Good morning!");
this._list.add("Good afternoon!");
}
}
/*
// some code for using example
ExampleClass ec = new ExampleClass();
// prints next text to console:
// ExampleClass: [Hello!, Ciao!, Good morning!, Good afternoon!]
System.out.println(ec.toString());
*/
祝你今天愉快。 尤里
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.