List<String>集合转Long[]数组
1 | List<String> list = new ArrayList<>(); |
List<String>直接以toArray的方式转换Long数组是错误的,运行后报错:
1 | Exception in thread "main" java.lang.ArrayStoreException |
查看java.util.List.toArray(T[])方法,注释中明确写到:
@throws ArrayStoreException if the runtime type of the specified array is not a supertype of the runtime type of every element in this list 如果指定数组的运行时类型不是此列表中每个元素的运行时类型的超类型
明显Long类型不是String类型的超类。
可以通过下面的方式实现
1 | List<String> stringList = Arrays.asList("1", "2", "3"); |
引申:
如何实现 List<String> 转
List<Long> ?
实现方式:
1 | List<String> stringList = Arrays.asList("1", "2", "3"); |
java.util.List.toArray(T[]) 源码:
1 | /** |