首页 > 解决方案 > 从数组中删除元素。获取 null 而不是实际删除元素/索引

问题描述

我正在尝试从数组中删除一个元素。我遇到了一个问题,当我运行我的程序并删除某个索引时。我在应该完全删除元素/索引的地方得到空值。

我的输出是当我在 main 方法中执行 list.display() 时

汤姆、鲍勃、理查德

但是,在我执行 list.remove() 并运行程序之后。我明白了

空,空,理查德。

有小费吗?

public class MyArrayList implements MyList {

    private Object[] theList;


    public MyArrayList()
    {
        theList = new Object[0];
    }


    public boolean add(Object toAdd){

        if(toAdd != null) {
            Object[] temp = new Object[theList.length + 1];

            for(int i = 0; i < theList.length; i++) {
                temp[i] = theList[i];
            }
            temp[theList.length] = toAdd;
            theList = temp;
            return true;
        } else {
            return false;
        }
    }

 public Object remove(int index) {

        if (index >= 0 && index < theList.length) {

            Object[] temp = new Object[theList.length - 1];
            theList[index] = null;

            int j = 0;
            for (int i = 0; i < theList.length; i++) {
                if (i == index) {
                    continue;
                }
                temp[j++] = theList[i];
                theList = temp;
            }
            return temp;
        }
        return null;
    }
public class Main {

    public static void main(String[] args) {

        MyArrayList list = new MyArrayList();

        list.add("Tom");
        list.add("Bob");
        list.add("Richard");
        list.display();

        list.remove(0);
        list.remove(1);

        list.display();
        

    }
}

标签: java

解决方案


由于您的代码实现了代码中不可用的 MyList,因此我无法在您的代码上运行以下示例,但您可以在代码中使用以下逻辑。在 remove 方法中不需要额外的临时数组。由于它是一个数组,因此您可以从必须删除的索引开始遍历数组,并开始将下一个元素移动一步。

   public Object remove(int index) {
        if (theList == null || index < 0 || index >= theList.length) { 
        return theList; 
        }
        for (int i = index; i < theList.length; i++) {
            theList[i] = theList[i + 1];
        }
    
    return null;
}

如果基于某个阈值有更多空位,您可以修剪数组尾部。


推荐阅读