java-toArray详解

toArray方法是ArrayList提供的将List转为数组的一个非常方法的方法。其中有有两个重载方法。

method1:list.toArray()

返回:Object[]数组

public Object[] toArray() {
    return Arrays.copyOf(elementData, size);
}

method2:list.toArray(T[])

public <T> T[] toArray(T[] a) {
    if (a.length < size)
        // Make a new array of a's runtime type, but my contents:
        return (T[]) Arrays.copyOf(elementData, size, a.getClass());
    System.arraycopy(elementData, 0, a, 0, size);
    if (a.length > size)
        a[size] = null;
    return a;
}

返回:传入数组的类型的数组

代码演示一

//不带参数的toarray方法
String[] arr = (String[])list.toArray();

运行结果:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
	at com.test.sofaweb.demo.Demo4.toArrayDemo(Demo4.java:27)
	at com.test.sofaweb.demo.Demo4.main(Demo4.java:17)

备注:异常的原因是无法将Object类型的数组强转为String类型的数组

代码演示二

//参数的toarray方法,参数为小于list.size()的数组,list.size()为3
String[] arr = new String[1];
String[] arrNew = list.toArray(arr);
for (String s : arrNew) {
    System.out.println(s);
}
System.out.println(arr==arrNew);
运行结果
aa
bb
cc
false

备注:当入参数组length小于list.size(),会新建一个同类型的数组来保持list中的元素

代码演示三

//参数的toarray方法,参数为大于list.size()的数组,list.size()为3
String[] arr = new String[5];
String[] arrNew = list.toArray(arr);
for (String s : arrNew) {
    System.out.println(s);
}
System.out.println(arr==arrNew);

运行结果

aa
bb
cc
null
null
true

备注:当入参数组length小于list.size(),不会新建一个同类型的数组来保持list中的元素,并且会将超出list.size()的空间用“null”来填充

代码演示四

//参数的toarray方法,参数为等于list.size()的数组,list.size()为3
String[] arr = new String[list.size()];
String[] arrNew = list.toArray(arr);
for (String s : arrNew) {
    System.out.println(s);
}
System.out.println(arr==arrNew);

运行结果

aa
bb
cc
true
备注:当入参数组length小于list.size(),不会新建一个同类型的数组来保持list中的元素,并且也没有填充超出list.size()的空间一说,这样看来这种方法应该是开销最小的ListToArray的方式了。




  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值