Collection.add
is a pretty generic method (not in the sense of Java generics -- in the sense of being widely applicable). As such, they wanted a return value that would apply generally.
Some classes (like ArrayList
) always accept elements, and so will always return true
. You're right that in these cases, a return type of void
would be just as good.
But others, like Set
, will sometimes not allow an element to be added. In Set
's case, this happens if an equal element was already present. It's often helpful to know that. Another example is a bounded collection (that can only hold a certain number of elements).
You could ask, "can't code just check this manually?" For instance, with a set:
if (!set.contains(item)) {
set.add(item);
itemWasAdded(item);
}
This is more verbose than what you can do now, but not a whole lot:
if (set.add(item)) {
itemWasAdded(item);
}
But this check-then-act behavior isn't thread safe, which can be crucial in multithreaded applications. For instance, it could be that another thread added an equal item between you checking set.contains(item)
and the set.add(item)
in the first code snippet. In a multithreaded scenario, those two actions really need to be a single, atomic action; returning boolean
from the method makes that possible.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…