我想删除数组列表中的空元素,这将减小数组的大小

时间:2020-10-22 18:37:52

标签: java oop junit5

这是我删除空元素数量的方法:

@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]

2 个答案:

答案 0 :(得分:0)

您不会缩小内部array变量,因此其大小不会改变。 实际上,您甚至没有从列表表头中删除元素,只是将所有元素移到null元素的右边,我认为这不是预期的。

答案 1 :(得分:0)

我在您的代码中看不到任何可以从数组中删除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
相关问题