我可以使用Arrays.asList创建数组列表吗? [英] Can I create a list of array with Arrays.asList?

查看:49
本文介绍了我可以使用Arrays.asList创建数组列表吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我想创建一个包含Integer []数组的列表.但是

Say I want to create a List which contains Integer[] arrays. But

Integer[] foo = {1,2,3};
List<Integer[]> bar = Arrays.asList(foo);

第二行将不会编译,因为 Arrays.asList(foo)将返回包含三个Integer元素(即1、2、3)的List,而不是包含单个Integer的List []元素.

The second line wouldn't compile, because Arrays.asList(foo) will return a List with three Integer elements(namely 1, 2, 3), not a List with a single Integer[] element.

由于文档将asList方法的参数声明为T类型的varargs,所以我不明白为什么编译器不会将第二行解释为给定类型Integer []的单个参数.如何获取单个数组元素的列表?

Since the documentation states the parameter of asList method as varargs of type T, I don't understand why the compiler doesn't interpret the second line as single argument of type Integer[] given. How do I get a List of single Array element?

List<Integer[]> bar = new ArrayList<Integer[]>(Arrays.asList(foo));

这正是我真正想做的,但它也无法编译,原因与我相信的相同.

This is what I actually wanted to do, but it also doesn't compile, for the same reason I believe.

推荐答案

否.Arrays.asList 对当前数组进行投影并将第一维展平为 List.由于只有一维,因此所有这些元素都会收集到列表中.

No. Arrays.asList takes a projection of your current array and flattens the first dimension into a List. Since you only have one dimension, all of those elements get collected into the list.

如果您有 Integer [] [] ,您可以这样做.

注意: asList 接受 T 的变量(因此, T ... ),实际上是 T [] .如果用 Integer [] [] 代替,则会得到 Integer [] ,因为 Integer [] [] 的一维将满足 T ... 的类型要求.

Note: asList accepts a vararg of T (so T...), which is effectively T[]. If you substitute that with Integer[][], you get Integer[], since one dimension of your Integer[][] will satisfy T...'s type requirement.

这篇关于我可以使用Arrays.asList创建数组列表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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