Tuesday, June 9, 2015

Converting array to list in Android


Simple solution:

public void arrayToList() {

    String sArray[] = new String[]{"A", "B", "C"};
    // This will work as is. However, if you try to add another 
    // String then you will get java.lang.UnsupportedOperationException    
    List lList = Arrays.asList(sArray);

}

However, you can't add another value if you just use asList().


Solution: use new ArrayList()
public void arrayToList() {

    String sArray[] = new String[]{"A", "B", "C"};
    List lList = new ArrayList(Arrays.asList(sArray));        // now add(String) works    lList.add("D");}