Don't get me wrong - I understand why add methods deriving from Collection must return boolean, I just don't get why there is inconsistency with this one method - addAll both return boolean even though one of them doesn't have to.
CodePudding user response:
Collection methods also cover sets. For sets, any time you add to it, it might have no effect, since sets cannot contain duplicates. So the boolean is there to indicate whether the method actually changed the collection.
In general, such Collection methods return booleans to indicate whether the collection was actually modifed by the method call.
This does not apply to the List method add(index, element)
. Anything that would prevent this adding an element to the list at the specified index would indicate an error, so it would cause an exception to be thrown.
CodePudding user response:
The boolean return value is there to help you catch the case where you give it an empty list. The add
method will always change your list so the return value would just always be true.
CodePudding user response:
The JavaDoc of Collection says, that add(E element)
returns true
, if the collection has been changed. As there are collections that don't support duplicates, those won't be changed when adding an element that is already in the collection.
A List, on the other hand, supports duplicate elements. The JavaDoc of List says, that add(int index, E element)
shifts any subsequent elements to the right (adds one to their indices). That means, the list will be changed every time you call add(int index, E element)
.