为什么没有 ArrayList(T[] t) 构造函数? [英] Why there is no ArrayList(T[] t) constructor?
问题描述
以这种方式通过对象数组初始化列表是很常见的:
It is very common to initialize list by array of objects in such way:
Foo[] objs = ...;
ArrayList<Foo> list = new ArrayList<Foo>(Arrays.asList(objs));
我想知道,为什么 ArrayList 的设计者没有包含以数组为参数的构造函数,以便它可以像这样初始化:
I wonder, is there any reason why desiners of ArrayList didn't include constructor with array as parameter, so that it could be initialized like that:
ArrayList<Foo> list = new ArrayList<Foo>(objs);
它是否违反了某些原则、线程安全或其他什么?
May be it violates some principles, thread-safety or something else?
推荐答案
我不知道为什么它不在标准库中,但是 Guava 的 Lists
类具有 newArrayList
甚至有助于类型推断:
I don't know why it's not in the standard library, but Guava's Lists
class has newArrayList
which even helps with type inference:
ArrayList<Foo> list = Lists.newArrayList(objs);
(如果您经常使用Lists.newArrayList
,您可能希望静态导入它.)
(You may want to import Lists.newArrayList
statically if you use it a lot.)
这篇关于为什么没有 ArrayList(T[] t) 构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!