Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which Way of List Initialize Is Better

Tags:

java

I was wondering, which way of initialization of a list is better?


public class Main {
    private final List<String> l = new ArrayList<String>();

    {
        l.add("a");
        l.add("b");
        l.add("c");
    }
}

public class Main {

    private final List<String> l = new ArrayList<String>() {{
        l.add("a");
        l.add("b");
        l.add("c");        
    }};
}

like image 799
Cheok Yan Cheng Avatar asked Feb 03 '10 07:02

Cheok Yan Cheng


3 Answers

the former, since it doesn't create an anonymous class; check the reasons here

like image 22
dfa Avatar answered Sep 24 '22 23:09

dfa


Neither, because none is making the list immutable. I guess you want to make it immutable, when you use final. If thats not the case, I apologize for my assumption.

If I am correct in assuming that, you should have a look into Collections.unmodifiableList(). And the latter will come handy,

private final List<String> l = Collections.unmodifiableList(new ArrayList<String>() {{
        add("a");
        add("b");
        add("c");        
}});

Otherwise, dfa is correct in suggesting the former.

Another way can be this,

private final List<String> l = Collections.unmodifiableList(Arrays.asList("a", 
                                    "b", "c"));
like image 32
Adeel Ansari Avatar answered Sep 24 '22 23:09

Adeel Ansari


I prefer using static factory methods of the next kind:

public final class CollectionUtils {
    private CollectionUtils() {  
    }

    public static <T> List<T> list(T... data) {
        return Arrays.asList(data);
    }

    public static <T> ArrayList<T> newArrayList() {
        return new ArrayList<T>();
    }

    public static <T> ArrayList<T> newArrayList(T... data) {
        return new ArrayList<T>(list(data));
    }
}

So, you can use them in your code in the next way:

import static CollectionUtils.list;
import static CollectionUtils.newArrayList;

public class Main {
    private final List<String> l1 = list("a", "b", "c");
    private final List<String> l2 = newArrayList("a", "b", "c");
}

Thus you get relatively compact way of creating and populating lists and don't need to duplicate generic declarations. Note, that list method just creates list view of array. You cannot add elements to it later (or remove). Meanwhile newArrayList creates usual ArrayList object.

As Joachim Sauer noted, these utility methods (and many other useful things) can be found in Google Collections library (which is now a part of Guava project).

like image 67
Rorick Avatar answered Sep 23 '22 23:09

Rorick