我知道你可以在实例化过程中初始化一个数组,如下:
String[] names = new String[] {"Ryan", "Julie", "Bob"};
有没有办法对数组列表做同样的事情?或者我必须用array.add()单独添加内容?
我知道你可以在实例化过程中初始化一个数组,如下:
String[] names = new String[] {"Ryan", "Julie", "Bob"};
有没有办法对数组列表做同样的事情?或者我必须用array.add()单独添加内容?
当前回答
数组。asList可以在这里提供帮助:
new ArrayList<Integer>(Arrays.asList(1,2,3,5,8,13,21));
其他回答
这就是如何使用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<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")
选择的答案是: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));
或者只是在创建之后添加元素可能仍然是最有效的。
数组。asList可以在这里提供帮助:
new ArrayList<Integer>(Arrays.asList(1,2,3,5,8,13,21));