3 ms·
Both implementations are incorrect as they needlessly mutate the input list: List<String> namesNotStartingWithB = new ArrayList<>(); for (String name : nam
by wcummings 11y ago
Both implementations are incorrect as they needlessly mutate the input list:
List<String> namesNotStartingWithB = new ArrayList<>();
for (String name : names) {
if (!name.startsWith("B")) {
namesNotStartingWithB.add(name);
}
}
Imagine a scenario where you're filtering one of the arguments to a method: the input will be mutated with no indication to the caller (or in the method signature), causing bugs, iterator invalidation etc.
- newgame 11y agoGood additional point that demands repetition: Don't mutate arguments to a (public) method if not absolutely necessary. Just to be clear, that does not make the approaches "incorrect". The list "names" is not necessarily an argument to a method. It might be a local, intermediate result that does not have the risk of "mutation at a distance".
- kristianp 11y agoI know what you're trying to say, but the problem definition is to mutate the list, removing items that start with B.