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?
Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. Trims the capacity of this ArrayList instance to be the list's current size.
Return: It always return "true". Don't worry about the Boolean return value. It always there as other classes in the collections family need a return value in the signature when adding an element.
ArrayList uses an Array of Object to store the data internally. When you initialize an ArrayList, an array of size 10 (default capacity) is created and an element added to the ArrayList is actually added to this array. 10 is the default size and it can be passed as a parameter while initializing the ArrayList.
A Boolean expression is a Java expression that returns a Boolean value: true or false .
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With