简体   繁体   English

哪种列表初始化方式更好

[英]Which Way of List Initialize Is Better

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

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. 注意,该list方法只是创建数组的列表视图。 You cannot add elements to it later (or remove). 您以后不能向其添加元素(或删除)。 Meanwhile newArrayList creates usual ArrayList object. 同时newArrayList创建通常的ArrayList对象。

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). 正如Joachim Sauer所指出的,这些实用方法(以及许多其他有用的东西)可以在Google Collections库中找到(它现在是Guava项目的一部分)。

the former, since it doesn't create an anonymous class; 前者,因为它不会创建一个匿名类; check the reasons here 检查原因在这里

Neither, because none is making the list immutable. 也没有,因为没有一个使列表不可变。 I guess you want to make it immutable, when you use final . 当你使用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() . 如果我认为这是正确的,你应该看看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. 否则,dfa建议前者是正确的。

Another way can be this, 另一种方式可以是这样,

private final List<String> l = Collections.unmodifiableList(Arrays.asList("a", 
                                    "b", "c"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM