在JAVA中同时使用对象和另一个列表初始化最终列表?

时间:2017-05-25 12:12:53

标签: java arrays list arraylist initialization

我有一个常量的最终列表,我想用一些对象初始化,我想同时添加一个列表,这在语法上是否可以用Java?

 public static final List<String> MY_LIST = Arrays.asList(new String [] { "Java","Python","Lisp","C#"});

 public static final List<String> SUB_LIST = Arrays.asList(new String [] {
"Cobol","Pascal"});

现在有一种方法可以在SUB_LIST与其他对象一起初始化时将MY_LIST添加到MY_LIST吗?

以简单的伪代码方式,

List A = {"obj1","obj2", addALL(List B)}

谢谢大家。我终于选择了这个解决方案:

public static final List<String> MY_LIST = Collections.unmodifiableList(new ArrayList<String>(){{
addAll(Arrays.asList(new String [] {"Java","Python","Lisp","C#"}));
addAll(SUB_LIST);}});

5 个答案:

答案 0 :(得分:2)

只有对列表的引用才是最终的,而不是列表本身。如果你想确保它在初始化后没有改变,你可能真的想让列表不可修改。

一种解决方案是:

public static final List<String> SUB_LIST = Collections.unmodifiableList(
                                              Arrays.asList("Cobol","Pascal"));

public static final List<String> MY_LIST = Collections.unmodifiableList(
                                              buildMyList(SUB_LIST));

private static List<String> buildMyList(List<String> subList) {
  List<String> myList = new ArrayList<> ();
  Collections.addAll(myList, "Java", "Python", "Lisp", "C#");
  myList.addAll(subList);
  return myList;
}

答案 1 :(得分:1)

public static final List<String> MY_LIST = new ArrayList<String>() {{
    addAll(Arrays.asList(new String [] { "Java","Python","Lisp","C#"}));
    addAll(SUB_LIST);
}} ;

public static final List<String> SUB_LIST = Arrays.asList(new String [] {
        "Cobol","Pascal"});

在这里你应该明确地声明List的真实类型(在这个例子中是ArrayList)。

答案 2 :(得分:0)

如果您使用的是Java 8和流,则可以执行以下操作:

private static final List<String> SUB_LIST = Collections.unmodifiableList(
            Arrays.asList("2#3#1#0", "1#0#4#1", "9#2#5#0", "4#2#3#2", "1#1#2#1"));

private static final List<String> MY_LIST = Collections.unmodifiableList(
            Stream.concat(Stream.of("s1", "s2"), SUB_LIST.stream()).collect(Collectors.toList()));

这样您就不需要定义辅助方法了。

答案 3 :(得分:0)

当你执行Arrays.asList时,它会在Arrays类中返回一个不支持addall功能的ArrayList内部类。所以如果你在集合框架中传递给ArrayList,你可以添加你所有的子列表

List<String> MY_LIST = new ArrayList<>(Arrays.asList(new String[] { "Java", "Python", "Lisp", "C#" })) ;

            List<String> SUB_LIST = Arrays.asList(new String[] { "Cobol", "Pascal" });
            MY_LIST.addAll(SUB_LIST);
            System.out.println(MY_LIST);

答案 4 :(得分:0)

您可以使用静态块来设置静态最终字段,使其更具可读性。

    public static final List<String> MY_LIST; 

    public static final List<String> SUB_LIST; 

    static {
    MY_LIST = new ArrayList<String> (Arrays.asList(new String[] { "Java",
            "Python","Lisp","C#"}));
    SUB_LIST = new ArrayList <String> (Arrays.asList(new String [] {"Cobol",
            "Pascal"}));
    MY_LIST.addAll(SUB_LIST);
    }