Reputation: 1
i have an arraylist called Module, i want to create a method that will delete a module from the ArrayList based on the index passed as the parameter. this is what i have so far but it isn't working. any suggestions please (beginner)? Simon
/**
* 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);
}
Upvotes: 0
Views: 950
Reputation: 45104
Delete doesn't seem to be an ArrayList method.
Try using remove, and don't forget to override the equals method.
Take a look at the api:
Removes the first occurrence of the specified element from this list, if it is present. If the list does not contain the element, it is unchanged. More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists). Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call).
Upvotes: 1
Reputation: 26118
In the example the method is taking a Module
object not the index so you need to get the index of the object theModule
first then use that index to remove the object from the list:
public void deleteModule (Module theModule)
{
int moduleIndex = modules.indexOf(theModule);
modules.remove(moduleIndex);
}
However it not really necessary to do this, the ArrayLists support a remove method that take the object to remove as a parameter:
public void deleteModule (Module theModule)
{
modules.remove(theModule);
}
The problem in your case is that you are calling modules.delete(theModule); instead of modules.remove(theModule);
Upvotes: 0
Reputation: 24499
First of all, I can't really see how Module
is an index.
The correct way of removing element from ArrayList based on index is:
//ie:
int index = 1;
modules.remove(index); //Will remove the second element in the arraylist
If you want to remove the Module
which is in the modules arraylist, you can do this by sending the module as parameter to the remove method
modules.remove(module);
However you must ensure Module has correctly implemented hashCode() and equals(). Normally all standard IDE's can generate this for you.
Upvotes: 0