java - 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);
}
}
解决方案
除非您允许未使用的数组条目,否则您不能在不创建新数组的情况下从数组中删除对象。数组具有固定长度。但是,删除一个数组的条目将不得不更改此长度或将一个条目留空。
第一种方法是,只清除应删除的条目:
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;
}
推荐阅读
- c++ - 前向申报可以自动化吗?
- javascript - XPages View onClick 模态对话框显示
- python - 从文件末尾删除第一个逗号
- python - 密码检查器尝试 2
- flutter - 如何将这些 FlatButton 转换为 Switch
- javascript - 根据输入字段对数据列表项进行排序
- c# - 寻找多个扩展名和多个字符串格式的文件夹
- bash - 读取bash中命令后显示的表的方法是什么
- google-cloud-platform - Dialogflow 内联编辑器功能异常:Webhook 调用失败。错误:未知
- javascript - 将字符串从 html 表单返回到烧瓶