package practice;
import java.util.ArrayList;
import java.util.List;
public class ElementTransfer {
public static void main(String[] args) {
/**
* 方法一
*/
int[] oldArr = { 1, 3, 4, 5, 0, 0, 6, 6, 0, 5, 4, 7, 6, 7, 0, 5 };
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < oldArr.length; i++) {
if (oldArr[i] != 0) {
list.add(oldArr[i]);
}
}
System.out.println("原数组中的元素:");
for (int i = 0; i < oldArr.length; i++) {
System.out.print(oldArr[i] + " ");
}
System.out.println("\n\n新数组中的元素:");
Object[] newArr = list.toArray();
for (Object object : newArr) {
System.out.print(object + " ");
}
/**
* 方法二
*/
// int[] oldArr = { 1, 3, 4, 5, 0, 0, 6, 6, 0, 5, 4, 7, 6, 7, 0, 5 };
// int[] newArr = new int[oldArr.length];
// int index = 0; // 定义新数组下标变量
// for (int i = 0; i <
Java数组元素剔除0后存入新数组
最新推荐文章于 2021-12-19 14:33:10 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)