java - 从数组中删除元素。获取 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();
}
}
解决方案
由于您的代码实现了代码中不可用的 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;
}
如果基于某个阈值有更多空位,您可以修剪数组尾部。
推荐阅读
- ruby-on-rails - 使用字符串结尾字符 (/z) 的 AR 查询中的正则表达式返回空的 AR 关系;使用行尾 ($) [PG] 返回预期结果
- python - 特定点python上的微分方程的解
- python - MDExpansion 面板 - kivy.properties.DictProperty' 对象没有属性 'panel_container'
- sql - 在 SQL Anywhere 中使用 AS 后无法连接两个表
- typescript - 推送后打开表单
- javascript - setState 如何在索引中排列?反应式
- amazon-web-services - AWS - 在免费套餐上使用 p2x.large
- svg - 在 JasperReports 中使用内联 base64 图像解析 Batik SVG
- docker - 如何将 apache 公共 url 重定向到 docker 容器?
- azure - 为什么只有通过应用程序网关访问时,我才会在应用服务上收到 502 ERROR_INTERNET_CONNECTION_ABORTED?