ArrayList如何转换为int[]数组


网上搜Arraylist和数组互相转换的方法时,举的例子都是String类型的。比如:

 

 

 

但是对于int类型如果这样写:

ArrayList<Integer> a=new ArrayList<Integer>();
int[] array=(int[])a.toArray(new int[size]);//会报错
则会报错,这是因为int[]并不等同于Integer[]。因此如果换成Integer[]数组,则能正确运行。
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
Integer[] array = list.toArray(new Integer[list.size()]);//能正确运行
for(int element:array){
System.out.println(element);
}

 


如果非得希望得到int[]的话,只能用循环赋值来得到了。

int[] d = new int[list.size()];
for(int i = 0;i<list.size();i++){
d[i] = list.get(i);
}
如果既不想用循环,又想要得到int[],那就只能在jdk8中使用IntStream了。 

 




原文链接:https://blog.csdn.net/huanghanqian/article/details/73920439


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM