我正在将一个空 String 数组(我可以从中间件获取)转换为 List 。
对于转换过程,我使用了 Arrays.asList (请参阅下面的代码),它抛出 java.lang.UnsupportedOperationException 。
public class Ramddd {
public static void main(String args[]) {
String[] words = null;
if (words == null) {
words = new String[0];
}
List<String> newWatchlist = Arrays.asList(words);
List<String> other = new ArrayList<String>();
other.add("ddd");
newWatchlist.addAll(other);
}
}
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(Unknown Source)
at java.util.AbstractList.add(Unknown Source)
at java.util.AbstractCollection.addAll(Unknown Source)
at Ramddd.main(Ramddd.java:18)
如果我使用,我不会收到此错误
List<String> mylist = new ArrayList<String>();
for (int i = 0; i < words.length; i++) {
mylist.add(words[i]);
}
这形成了一个正确的List
,并且任何诸如addALL
、removeALL
之类的操作似乎都不错,但不想采用这种for循环方法,因为这可能会导致性能下降。
请让我知道将 String 数组转换为 ArrayList 的最佳且安全的方法是什么。
最佳答案
以下怎么样:
public class Ramddd {
public static void main(String args[]) {
String[] words = getWords();
if (words == null) {
words = new String[0];
}
List<String> other = new ArrayList<String>(Arrays.asList(words));
other.add("ddd");
}
}
就性能而言,我不认为这是值得担心的事情,除非您有一个非常巨大的字符串数组。
关于java - 从 String 数组到 ArrayList 转换的性能相关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14740486/