I'm having some trouble with removing an item from an ArrayList, specifically removing an item which has been specified and passing the id of this item to the remove() function.
DockService service = new DockServiceImpl();
// This should remove the boat with the ID: NV 2345 KO
service.removeBoat("NV 2345 KO");
if (service.getDock().getDockedBoats().size() == 2) {
System.out.println("Test 2 - Removing a boat: Passed.");
} else {
System.out.println("Test 2 - Removing a boat: Failed.");
}
This is the ArrayList in a separate class
public static List<Boat> createBoatList() {
List<Boat> boatList = new ArrayList<>();
Boat firstBoat = new Boat("NV 1234 VN", 1000);
Boat secondBoat = new Boat("NV 2345 KO", 1500);
Boat thirdBoat = new Boat("NV 3053 NZ", 2000);
boatList.add(firstBoat);
boatList.add(secondBoat);
boatList.add(thirdBoat);
return boatList;
}
This is the dock class which contains the get set methods
public Dock(String name, int capacity) {
this.name = name;
this.capacity = capacity;
this.dockedBoats = new ArrayList<>();
}
public List<Boat> getDockedBoats() {
return dockedBoats;
}
So in my removal method, i have tried this
private Dock dock;
public boolean removeBoat(String boatId) {
System.out.println(">>> Deleting boat.");
this.dock.getDockedBoats().remove(boatId);
return false;
}
But the remove(boatId) does not remove the boat from the arraylist, any help would be greatly appreciated
Boatobjects in yourList- then you are trying to remove oneBoatby passing aString- this will not work. You need to first find the matchingBoatobject given the parameter and then remove that object from the listreturn this.dock.getDockedBoats().remove(boatId);instead of justreturn false;