所以我有
int[] a = {0, 0, 0, 0, 4, 2, 3, 9};
int[] b = {0, 0, 0, 0, 0, 0, 1, 3};
如何才能删除所有值为 0 的元素,并且每个数组都不会分配任何额外的不必要的空间。
int[] a = {4, 2, 3, 9};
int[] b = {1, 3};
最佳答案
Java 8 解决方案:
a = Arrays.stream(a).filter(v -> v != 0).toArray();
不需要 Java 8 的解决方案:
int count = 0;
for (int i = 0; i < a.length; i++)
if (a[i] != 0)
a[count++] = a[i];
a = Arrays.copyOf(a, count);
但是,我认为最好的解决方案是使用 ArrayList<Integer>
对于这种事情。
关于java - 删除数组中的 0 值并调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32938831/