I am converting an empty String array (which i may get from middleware) to List .
For Conversion process i used Arrays.asList (Please see below code ) which is throwing an 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)
I dont get this Error if i use
List<String> mylist = new ArrayList<String>();
for (int i = 0; i < words.length; i++) {
mylist.add(words[i]);
}
This forms an proper List
and any operations like addALL
, removeALL
seems good , but dont want to go to this for loop approach , as it may result in performance .
Please let me know what is the best and safe approach for converting a String array to ArrayList .