这是我删除空元素数量的方法:
@Override
public void removeAt(int index) {
int count = 0;
for(int i = index; i < this.array.length -1; i++){
array[i] = array[i + 1];
if(Arrays.toString(array).contains("null")) {
count = count + 1;
System.out.println("the number of null it has is " + count);
}
}
System.out.println(Arrays.toString(array));
}
这是我对removeAt方法的测试:
@Test
@DisplayName("remove at index 0, then check size, went from 11 to 10")
void t8_removeAt() {
MutableArray<String> ma = new MutableArray<String>();
//add 11 items to the array
for(int i = 0; i < 11; i++) {
ma.append("number_" + i);
}
//delete element 0
ma.removeAt(1);
int actual = ma.size();
int expected = 10;
assertEquals(expected, actual);
}
这就是结果:
the number of null it has is 1
the number of null it has is 2
the number of null it has is 3
the number of null it has is 4
the number of null it has is 5
the number of null it has is 6
the number of null it has is 7
the number of null it has is 8
the number of null it has is 9
the number of null it has is 10
the number of null it has is 11
the number of null it has is 12
the number of null it has is 13
the number of null it has is 14
the number of null it has is 15
the number of null it has is 16
the number of null it has is 17
the number of null it has is 18
[number_0, number_2, number_3, number_4, number_5, number_6, number_7, number_8, number_9, number_10, null, null, null, null, null, null, null, null, null, null]
您没有收缩内部array
变量,因此其大小不会改变。事实上,你甚至没有从列表中删除元素,只是将所有元素移到null元素的右边,我认为这不是预期的。
我在您的代码中没有看到任何可以从数组中删除null
元素的语句。一个简单的解决方案是将给定的数组转换为ArrayList
,然后使用Iterator
迭代ArrayList
并删除null
元素。删除完null
元素后,将ArrayList
转换回数组。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Original array
String[] array = { "a", "b", null, "c", null, null, "d" };
int originalSize = array.length;
// Delete null elements
List<String> list = new ArrayList<>(Arrays.asList(array));
Iterator<String> itr = list.iterator();
while (itr.hasNext()) {
if (itr.next() == null) {
itr.remove();
}
}
// Convert list to array and assign it to original array reference
array = list.toArray(new String[0]);
System.out.println(Arrays.toString(array));
System.out.println("Number of null elements deleted: " + (originalSize - array.length));
}
}
输出:
[a, b, c, d]
Number of null elements deleted: 3