首页 > 解决方案 > How can I remove an element of array without using list or collection methods

问题描述

I should build a class like an array class and I should consider a remove method that is able to remove an element by index and by value.

public void delet(int index) {
    int shouldBeDelet=Containor[index];
    Containor copy=new Containor();
    int numberOfReapeat=0;
    rear=0;
    for (int i=0 ;i<Containor.length;i++){
        if (Containor[i]!=shouldBeDelet){
            copy.add(Containor[i]);
        }
        else numberOfReapeat++;
    }
    for (int i=0;i<copy.size()-numberOfReapeat-1;i++){
        Containor[i]=copy.get(i);
    }
}

标签: javaarrays

解决方案


除非您允许未使用的数组条目,否则您不能在不创建新数组的情况下从数组中删除对象。数组具有固定长度。但是,删除一个数组的条目将不得不更改此长度或将一个条目留空。

第一种方法是,只清除应删除的条目:

public void remove(int indexToRemove){
  this.array[indexToRemove] = null;
}

我不推荐这种解决方案,因为您实际上不会从数组中删除任何元素,只需使用null;覆盖它即可。

第二种方法是删除条目并将每个后续元素向左移动(较低的索引)。但是,这只是将 null 元素移动到列表的末尾。

public void remove(int indexToRemove){
  for (int i = indexToRemove+1; i < this.array.length; i++) {
    this.array[i-1] = this.array[i];
  }

  this.array[this.array.length] = null;
}

更好的方法是创建一个包含旧数组的 n-1 个条目的新数组,方法是将旧数组的每个条目添加到新数组中,但要删除的条目除外:

public void remove(int indexToRemove){
  YourClass[] newArray = new YourClass[this.array.length-1];

  int newArrayIndex = 0;
  for (int oldArrayIndex = 0; oldArrayIndex < this.array.length; oldArrayIndex++) {
    if (oldArrayIndex != indexToRemove) {
      newArray[newArrayIndex] = this.array[oldArrayIndex];
      newArrayIndex++;
    }
  }

 this.array = newArray;
}

推荐阅读