我知道你可以在实例化过程中初始化一个数组,如下:

String[] names = new String[] {"Ryan", "Julie", "Bob"};

有没有办法对数组列表做同样的事情?或者我必须用array.add()单独添加内容?


在Java中,列表没有文字语法,所以你必须使用.add()。

如果你有很多元素,这有点啰嗦,但你可以:

使用Groovy或类似的东西 使用arrays . aslist(数组)

2看起来像这样:

String[] elements = new String[] {"Ryan", "Julie", "Bob"};
List list = new ArrayList(Arrays.asList(elements));

但是这会导致一些不必要的对象创建。

Yes.

new ArrayList<String>(){{
   add("A");
   add("B");
}}

这实际上是在创建一个派生自ArrayList<String>的类(外部花括号的功能),然后声明一个静态初始化器(内部花括号的功能)。这实际上是包含类的内部类,所以它有一个隐式This指针。这不是问题,除非你想序列化它,或者你希望外部类被垃圾收集。

我知道Java 7将提供额外的语言结构来完成您想要的工作。

编辑:最近的Java版本为创建这样的集合提供了更多可用的函数,并且值得研究以上(在这些版本之前提供)

数组。asList可以在这里提供帮助:

new ArrayList<Integer>(Arrays.asList(1,2,3,5,8,13,21));

这是你能得到的最接近的答案:

ArrayList<String> list = new ArrayList(Arrays.asList("Ryan", "Julie", "Bob"));

你可以用更简单的方法:

List<String> list = Arrays.asList("Ryan", "Julie", "Bob")

查看数组的源代码。asList,它构造一个数组列表,但默认情况下转换为List。所以你可以这样做(但对新的jdk不可靠):

ArrayList<String> list = (ArrayList<String>)Arrays.asList("Ryan", "Julie", "Bob")
Arrays.asList("Ryan", "Julie", "Bob");

这就是如何使用op4j Java库(1.1。12月10日发布):-

List<String> names = Op.onListFor("Ryan", "Julie", "Bob").get();

这是一个非常酷的库,可以节省你大量的时间。

这个怎么样?

ArrayList<String> names = new ArrayList<String>();
Collections.addAll(names, "Ryan", "Julie", "Bob");

选择的答案是:ArrayList<Integer>(Arrays.asList(1,2,3,5,8,13,21));

但是,重要的是要理解所选答案在创建最终数组之前会在内部多次复制元素,并且有一种方法可以减少一些冗余。

让我们先来了解一下发生了什么:

First, the elements are copied into the Arrays.ArrayList<T> created by the static factory Arrays.asList(T...). This does not the produce the same class as java.lang.ArrayListdespite having the same simple class name. It does not implement methods like remove(int) despite having a List interface. If you call those methods it will throw an UnspportedMethodException. But if all you need is a fixed-sized list, you can stop here. Next the Arrays.ArrayList<T> constructed in #1 gets passed to the constructor ArrayList<>(Collection<T>) where the collection.toArray() method is called to clone it. public ArrayList(Collection<? extends E> collection) { ...... Object[] a = collection.toArray(); } Next the constructor decides whether to adopt the cloned array, or copy it again to remove the subclass type. Since Arrays.asList(T...) internally uses an array of type T, the very same one we passed as the parameter, the constructor always rejects using the clone unless T is a pure Object. (E.g. String, Integer, etc all get copied again, because they extend Object). if (a.getClass() != Object[].class) { //Arrays.asList(T...) is always true here //when T subclasses object Object[] newArray = new Object[a.length]; System.arraycopy(a, 0, newArray, 0, a.length); a = newArray; } array = a; size = a.length;

因此,我们的数据被复制3x,只是为了显式地初始化数组列表。如果我们强制Arrays.AsList(T…)构造一个Object[]数组,我们可以把它降到2x,这样ArrayList以后就可以采用它,具体操作如下:

(List<Integer>)(List<?>) new ArrayList<>(Arrays.asList((Object) 1, 2 ,3, 4, 5));

或者只是在创建之后添加元素可能仍然是最有效的。