Java List集合转数组的两种重载方法

前几天写代码碰到了这个场景,要将一个List转换成数组,

List<String> list = new ArrayList<String>();
...
list.add(...);
...
JSONObject obj = new JSONObject();
obj.put("result", list.toArray());

ArrayList提供了将List转为数组的简单方法toArray,他有两个重载的方法,

(1) list.toArray();,将list直接转为Object[]数组。

(2) list.toArray(T[] a);,将list转换为你所需要类型的数组,我们用的时候会转换为与list内容相同的类型。

像我这种不明真相的朋友,可能选择第一个,毕竟看着简单,

ArrayList<String> list=new ArrayList<String>();
for (int i = 0; i < 10; i++) {
    list.add(""+i);
}
String[] array= (String[]) list.toArray();

但是运行起来,就会提示,

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; 
cannot be cast to [Ljava.lang.String;

原因很清楚,不能将Object[]转换为String[],如果要转换,只可以取出每一个元素,再进行转换,因为在Java中的强制类型转换只是针对单个对象的,不能将整个数组转换成另外一种类型的数组,

Object[] arr = list.toArray();
for (int i = 0; i < arr.length; i++) {
    String e = (String) arr[i];
    System.out.println(e);
}

因此,我们转向第二种,

String[] array =new String[list.size()];
list.toArray(array);

最开始的示例,使用第二种重载,如下所示,

List<String> list = new ArrayList<String>();
...
list.add(...);
...
JSONObject obj = new JSONObject();
obj.put("result", list.toArray(new String[list.size()]));

从toArray()的help,我们看到,这种形式能准确地控制array的运行时类型,

Like the toArray() method, this method acts as bridge betweenarray-based and collection-based APIs. Further, this method allows precise control over the runtime type of the output array, and may,under certain circumstances, be used to save allocation costs

因此,当我们需要将集合转成数组的时候,尽量选择list.toArray(T[] a),避免不必要的类型转换错误。

近期更新的文章:

PG逻辑复制的REPLICA IDENTITY设置

最近碰到的几个问题

Linux的dd指令

Oracle、SQL Server和MySQL的隐式转换异同

JDK的版本号解惑

文章分类和索引:

公众号700篇文章分类和索引

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值