Reputation: 246
My teacher gave me this analogy for a method I am writing. I still don't get why the add method returns a boolean?
Wouldn't it make more sense for it to return nothing?
Upvotes: 7
Views: 11211
Reputation: 133609
This comes from Collection<E>
interface, since the interface is used as an ancestor class for all kinds of collections, it makes sense to return a boolean
to inform if add
effectively changed the collection.
This is useful for collections like Set<T>
which doesn't change if the element added was already present inside the collection. In case of a List<T>
Java enforces by design to return true
, so if you want to notify the caller that the operation didn't succeed you must find another way (eg. throw an exception).
This is clearly stated in Collection<E>.add
documentation:
If a collection refuses to add a particular element for any reason other than that it already contains the element, it must throw an exception (rather than returning false). This preserves the invariant that a collection always contains the specified element after this call returns.
Basically the value returned doesn't indicate failure but if a successful add operation changed the collection. Any failure must be notified by throwing an exception.
Upvotes: 14
Reputation: 269
Simply put (and this is what helped me understand it). the boolean you're returning indicates that your add()
was successful.
Consider this, if you didn't return a boolean, how would you know that you successfully added something? You'd have to manually check to see that you indeed added something. It's "unnecessary", but it's clever.
Upvotes: 2
Reputation: 201467
The Javadoc for ArrayList.add(E)
explains that it
Returns: true (as specified by Collection.add(E))
Which says
Returns: true if this collection changed as a result of the call
If it didn't return a boolean
, then a caller would have to test the List
or check an Exception
or there would be no way to tell if the call succeeded. I think it was easier (and faster) to return a boolean
.
Upvotes: 3