Looking at the javadoc I saw the that an ArrayList has an overloaded add method:
public boolean add(E e)
Appends the specified element to
Because it's an extra information which doesn't cost anything and can be useful in certain situations. For example:
Set<String> set = new HashSet<String>();
set.add("foobar");
boolean wasAlreadyThere = set.add("foobar");
Otherwise you would have to do
boolean wasAlreadyThere = set.contains("foobar");
set.add("foobar");
which requires twice the work (first you have to lookup, then lookup again to add).
because it is often useful to know if something was actually added, or alternately was already there.
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.