关于list.toArray的一点内容

本文详细介绍了Java中List的toArray方法的使用方式及注意事项,通过示例展示了如何将List转换为数组,并解释了toArray方法的工作原理及其与指定数组的关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于list.toArray的一点内容:
List<String> list = new ArrayList<String>();
list.add("str1");
list.add("str2");
String[] arry = new String[list.size()];
arry = list.toArray(new String[0]);
//一般情况下用下面这句
//list.toArray(arry);
System.out.println(arry[0]);
System.out.println(arry[1]);

[i]str1
str2[/i]
List<String> list = new ArrayList<String>();
list.add("str1");
list.add("str2");
String[] arry = new String[list.size()];
String[] arry2 = new String[list.size()];
arry2 = list.toArray(arry);
System.out.println(arry[0]);
System.out.println(arry[1]);
System.out.println(arry2[0]);
System.out.println(arry2[1]);
arry[0] = "strElse";
System.out.println(arry[0]);
System.out.println(arry2[0]);

[i]str1
str2
str1
str2
strElse
strElse[/i]

从执行结果应该可以看出点端倪了。

最后附上API里面关于这个方法的说明:

[b]T> T[] toArray(T[] a)[/b]
返回以正确顺序包含列表中所有元素的数组;返回数组的运行时类型是指定数组的运行时类型。遵守 Collection.toArray(Object[]) 方法的常规协定。

指定者:
接口 [color=blue]Collection<E>[/color] 中的 toArray
参数:
a - 要存储列表中元素的数组,如果它足够大的话;否则为此目的分配一个运行时类型相同的新数组。
返回:
包含列表中元素的数组。
抛出:
[color=blue]ArrayStoreException[/color] - 如果指定数组的运行时类型不是此列表中每个元素的运行时类型的超类型。
[color=blue]NullPointerException[/color] - 如果指定数组为 null。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值