前几天写代码碰到了这个场景,要将一个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),避免不必要的类型转换错误。
近期更新的文章:
《Oracle、SQL Server和MySQL的隐式转换异同》
文章分类和索引:
文章转载自bisal的个人杂货铺,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。
评论
相关阅读
Oracle 发布 Java 24
通讯员
128次阅读
2025-03-19 10:08:51
Oracle 正式发布 Java 24
千钧
89次阅读
2025-03-20 11:26:28
Java 与 Oracle 集成
芃芃
32次阅读
2025-03-19 21:21:38
Java的SPI机制详解
京东云开发者
27次阅读
2025-03-05 11:47:12
从零玩转GaussDB:Java开发者必学的JDBC操作指南
数据库运维之道
17次阅读
2025-03-19 11:20:48
Java反射大揭秘:程序员的“偷窥”与“开挂”指南
让天下没有难学的编程
5次阅读
2025-03-28 15:02:40
Java反射大揭秘:程序员的“偷窥”与“开挂”指南
让天下没有难学的编程
4次阅读
2025-03-23 22:09:15