Pawan
Pawan

Reputation: 32321

Performance related for conversion from String array to ArrayList

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 .

Upvotes: 1

Views: 156

Answers (2)

Paul Vargas
Paul Vargas

Reputation: 42030

The method java.util.Arrays.asList(T...) returns a fixed-size list backed by the specified array. This implementation of List for this method (java.util.Arrays.ArrayList) don't have support for these methods. See the documentation for the java.util.AbstractList.

If you know the total size of your list of words, you can init the capacitity for ArrayList, adding n elements requires O(n) time. If you don't know the final size, use LinkedList.

See more in List Implementations (The Java Tutorials > Collections > Implementations).

Upvotes: 1

John Ericksen
John Ericksen

Reputation: 11113

How about the following:

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");
    }
}

In terms of performance, I don't this this is something to worry about, unless you have a really gigantic array of Strings.

Upvotes: 1

Related Questions