Why does the Java ArrayList class return a Boolean value to add?
My teacher gave me this analogy to the method I was writing I still don't understand why the add method returns a Boolean value?
Would it make more sense if it didn't return?
Solution
This comes from the collection < E > interface. Because the interface is used as the ancestor class of various collections, it returns a Boolean value to tell whether add has effectively changed the collection
This is very useful for collections such as set < T > if the added element already exists in the collection, the collection will not change In the case of list < T >, Java forces true by design, so if you want to notify the caller that the operation is unsuccessful, you must find another method (such as throwing an exception)
This is in the collection < E > The add document clearly states:
Basically, the returned value does not indicate failure, but if a successful add operation changes the collection Any failure must be notified by throwing an exception