1

可能重复:
在 Java java 中将数组分配给 ArrayList
:如何将此字符串转换为 ArrayList?
如何将字符串转换为 ArrayList?

我有这个String

["word1","word2","word3","word4"]

上面的文本不是数组,而是服务器通过 GCM(Google Cloud Messaging)通信返回的字符串。更具体地说,在 GCM 类中,我有这个:

protected void onMessage(Context context, Intent intent) {

String message = intent.getExtras().getString("cabmate");

   }

消息的价值String["word1","word2","word3","word4"]

有没有办法将它转换成JavaListArrayListJava?

4

3 回答 3

3
Arrays.asList(String[])

返回一个List<String>

于 2013-01-12T02:19:26.483 回答
1

像这样的东西:

/*
@invariant The "Word" fields cannot have commas in thier values or the conversion
to a list will cause bad field breaks. CSV data sucks...
*/
public List<String> stringFormatedToStringList(String s) {
  // oneliner for the win:
  return Arrays.asList(s.substring(1,s.length()-1).replaceAll("\"","").split(","));
  // .substring  removes the first an last characters from the string ('[' & ']')
  // .replaceAll removes all quotation marks from the string (replaces with empty string)
  // .split brakes the string into a string array on commas (omitting the commas)
  // Arrays.asList converts the array to a List
}
于 2013-01-12T02:51:50.940 回答
1
String wordString = "[\"word1\", \"word2\", \"word3\", \"word4\"]";
String[] words = wordString.substring(1, wordString.length() - 2).replaceAll("\"", "").split(", ");
List<String> wordList = new ArrayList<>();
Collections.addAll(wordList, words);

这将做你想要的。请注意,我故意拆分", "以删除空格,.trim()在 for-each 循环中调用每个字符串然后添加到List.

于 2013-01-12T02:20:10.690 回答