patternjavaMinor
Remove item from a list, which (of the 2) methods is better?
Viewed 0 times
itemthebetterremovemethodswhichlistfrom
Problem
I have a
One of my co-workers suggested I should hold the object to be removed and remove it once we get out of the
Which one of the above is a good-to-have in the code?
List, and I have to delete one item from the list when I find it. I am using the code below to do that:Iterator iter = flist.iterator();
while (iter.hasNext()) {
Long deletedFiId = iter.next().getId();
if (deletedFiId.equals(fiId)) {
iter.remove();
break;
}
}One of my co-workers suggested I should hold the object to be removed and remove it once we get out of the
for loop, like this:MyClass deletedFiId = null;
for (MyClass dto: flist) {
if (dto.getId().equals(fiId)) {
deletedFiId = dto;
break;
}
if (deletedFiId != null)
fiList.remove(deletedFiId);Which one of the above is a good-to-have in the code?
Solution
The two methods are functionally identical.
The first method is faster to execute.
The first method is clearer for someone who doesn't know the code.
Unless there's an "else" you need (that is, logic to execute if the item can't be found), I can't think of a reason to prefer the second approach.
First approach wins.
The first method is faster to execute.
The first method is clearer for someone who doesn't know the code.
Unless there's an "else" you need (that is, logic to execute if the item can't be found), I can't think of a reason to prefer the second approach.
First approach wins.
Context
StackExchange Code Review Q#32777, answer score: 3
Revisions (0)
No revisions yet.