Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从Java中的ArrayList中删除_Java - Fatal编程技术网

从Java中的ArrayList中删除

从Java中的ArrayList中删除,java,Java,我有一个名为Module的arraylist,我想创建一个方法,根据作为参数传递的索引从arraylist中删除一个模块。这是我目前所拥有的,但它不起作用。初学者有什么建议吗?西蒙 /** * This method deletes a module object from the ArrayList * @param theModule The module object that will be deleted from the ArraList */ public void dele

我有一个名为Module的arraylist,我想创建一个方法,根据作为参数传递的索引从arraylist中删除一个模块。这是我目前所拥有的,但它不起作用。初学者有什么建议吗?西蒙

/**
 * This method deletes a module object from the ArrayList
 * @param theModule The module object that will be deleted from the ArraList
 */
public void deleteModule (Module theModule)
{
    modules.delete(theModule);
}
试试这个方法


一定要实现equals和hashcode,否则成员和单元测试将不会高兴。

Delete似乎不是ArrayList方法

尝试使用remove,不要忘记重写equals方法

看一看

删除第一次出现的 此列表中的指定元素,如果 它是存在的。如果列表中没有 如果包含该元素,则该元素将保持不变。 更正式地说,删除元素 以最低的指数i o==null?geti==null: o、 如果这样的元素 存在。如果此列表为空,则返回true 包含指定的元素或 如果此列表更改为 电话的结果


在本例中,该方法采用的是模块对象而不是索引,因此您需要先获取对象模块的索引,然后使用该索引从列表中删除该对象:

public void deleteModule (Module theModule)
{
    int moduleIndex = modules.indexOf(theModule);
    modules.remove(moduleIndex);
}
但是,实际上没有必要这样做,ArrayList支持一个remove方法,该方法将要删除的对象作为参数:

public void deleteModule (Module theModule)
{
    modules.remove(theModule);
}

本例中的问题是您正在调用modules.deletetethemodule;而不是modules.removetheModule

首先,我真的看不出模块是如何成为索引的

根据索引从ArrayList中删除元素的正确方法是:

//ie: 
int index = 1;
modules.remove(index); //Will remove the second element in the arraylist
如果要删除modules arraylist中的模块,可以将模块作为参数发送到remove方法

modules.remove(module);
然而,您必须确保模块正确地实现了hashCode和equals。
通常,所有标准IDE都可以为您生成此文件

你说的不工作是什么意思?有错误吗?请添加更多的代码,例如模块的定义。关于重写equals和hashCode,可能是最好的问答:你没有传递索引作为参数,而是传递对象本身。我有一个问题。。。您是否使用ide?如果使用ide,它不会显示编译错误吗?谢谢大家的反馈。看起来现在一切正常。西蒙
modules.remove(module);