为什么没有 ArrayList(T[] t) 构造函数? [英] Why there is no ArrayList(T[] t) constructor?

查看:29
本文介绍了为什么没有 ArrayList(T[] t) 构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以这种方式通过对象数组初始化列表是很常见的:

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?

推荐答案

我不知道为什么它不在标准库中,但是 GuavaLists 类具有 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆