Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java LinkedList...I am trying to use .remove() to remove an object from a Linked

ID: 3813047 • Letter: J

Question

Java LinkedList...I am trying to use .remove() to remove an object from a LinkedList by searching for an int value within the object. I wanted to try using a foreach loop to search, but I am wondering if the iterator is better. The LinkedList contains Car objects and I need to remove an object based on the owner number which is an int. For example: int ownerNumber = 123456. What I have been trying to do is the following:

LinkedList <Car> carList = new LinkedList<>();

public boolean removeCar(int ownerNumber){
  
for(Car car: carList){
if(car.contains(ownerNumber)){
return carList.remove(car);
}

}
  
}

Explanation / Answer


linked list:

for(ObjectType ob : obList) {
if(ob.getId() == id) {
obList.remove(ob);
break;
}
}

add & remove

for(Iterator<EmpDedup> iter = list.iterator(); iter.hasNext();) {
EmpDedup data = iter.next();
if (data.getRecord() == rec1) {
iter.remove();
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote