Arrays.asList(T[] 数组)?
所以有 Arrays.asList(T... a)
但这适用于可变参数。
如果我已经在 T[] a
中包含该数组怎么办?是否有一种方便的方法可以从中创建 List
,还是我必须手动执行以下操作:
static public <T> List<T> arrayAsList(T[] a)
{
List<T> result = new ArrayList<T>(a.length);
for (T t : a)
result.add(t);
return result;
}
So there's Arrays.asList(T... a)
but this works on varargs.
What if I already have the array in a T[] a
? Is there a convenience method to create a List<T>
out of this, or do I have to do it manually as:
static public <T> List<T> arrayAsList(T[] a)
{
List<T> result = new ArrayList<T>(a.length);
for (T t : a)
result.add(t);
return result;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
仅仅因为它与 varargs 一起工作并不意味着你不能正常调用它:
唯一棘手的一点是如果
T
是Object
,你应该使用强制转换来告诉编译器是否应该将参数包装在数组中:或
Just because it works with varargs doesn't mean you can't call it normally:
The only tricky bit is if
T
isObject
, where you should use a cast to tell the compiler whether it should wrap the argument in an array or not:or
您可能已经知道,有一个名为 java.util.Collections 它有许多有用的方法来处理智能数组,例如搜索和排序。
至于你的问题,Collection 接口指定了
add
、remove
和toArray
等方法。出于某种原因,API 的作者决定将add
和addAll
方法作为向用户提供的唯一输入函数。Java 列表无法添加对象数组的一种解释是,列表使用迭代器,并且迭代器的滚动(即转到下一个值)比数组更严格,数组不必拥有所有索引值i= (1、2、5、9、22...)。
此外,数组不是类型安全;也就是说,它们不能保证其所有元素都符合特定的超类或接口,而泛型(
List
是其中的成员)可以保证类型安全。因此,列表有机会使用add
方法验证每个项目。我认为您可以放心,将数组添加到列表的方法是在 Java 中实现此效果的最(如果不是最)有效的方法之一。
As you probably already know, there is a Static class called java.util.Collections which has a number of useful methods for dealing wit arrays such as searching and sorting.
As for your question, the Collection interface specifies methods to
add
,remove
andtoArray
, amongst others. For one reason or another, the API's authors decided that theadd
andaddAll
method will be the only input functions provided to the user.One explanation for why Java Lists cannot add arrays of objects is that Lists use an iterator and iterators are more strict in their scrolling (i.e. going to the next value) than Arrays which do not have to have all their index values i=(1, 2, 5, 9, 22, ...).
Also, Arrays are not type safe; that is, they cannot guarantee that all their elements conform to a specific super-class or interface, whereas generics (of which
List
is a member) can guarantee type safety. Hence, the list has the chance to validate each item using theadd
method.I think that you can rest assure that your method of adding an array to a list is one of the most (if not most) efficient way of achieving this effect in Java.