应使用 list.toarray(new t[0]) 安全转换,因无参版返回 object[] 强转会抛 classcastexception,而 [0] 版由 jvm 根据泛型创建正确类型数组,且线程安全、性能无损。

直接用 List.toArray() 得到的是 Object[],无法直接赋值给具体类型的数组(如 String[]、Integer[]),强行强转会触发 ClassCastException。安全还原的关键是**让泛型信息参与运行时数组创建**,即使用带类型数组参数的重载方法。
必须用 toArray(T[]) 重载,不能只用无参版
无参 toArray() 总是返回 Object[],即使 List 是 List<string></string>。而带参重载 list.toArray(new T[0]) 会根据传入数组的组件类型,返回正确类型的数组(JDK 1.5+ 支持)。
- ✅ 推荐写法:
String[] arr = list.toArray(new String[0]); - ❌ 危险写法:
String[] arr = (String[]) list.toArray();→ 运行时报错 - ⚠️ 次选写法:
String[] arr = list.toArray(new String[list.size()]);(可避免扩容,但语义不如[0]清晰)
为什么推荐传 new T[0] 而不是 new T[list.size()]
传空数组 new T[0] 是 JDK 官方推荐方式(见 ArrayList 源码注释),原因有二:
- 避免因并发修改导致
size()和实际元素数不一致,引发数组越界或截断 - 现代 JVM 对
new T[0]的分配开销极小,且多数集合实现(如 ArrayList)会直接创建精确大小的新数组,性能无损
对接旧 API 时的典型场景与写法
假设遗留方法签名为 void processNames(String[] names),而你手头是 List<string> nameList</string>:
-
安全调用:
processNames(nameList.toArray(new String[0])); -
兼容 null 安全(若 list 可能为 null):
processNames((nameList != null ? nameList.toArray(new String[0]) : new String[0])); -
处理基本类型包装类(如 Integer):
Integer[] ids = idList.toArray(new Integer[0]);(注意:不能直接转int[],需额外遍历拆箱)
特别注意:原始类型数组无法直接生成
List<integer></integer> 只能转成 Integer[],不能直接得到 int[]。若旧 API 要求 int[],必须手动转换:
-
int[] ints = list.stream().mapToInt(Integer::intValue).toArray();(Java 8+) - 或传统循环:
int[] ints = new int[list.size()]; for (int i = 0; i
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










