Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the Java ArrayList class return a boolean for add?

Tags:

java

arraylist

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?

like image 355
RostSunshine Avatar asked Dec 04 '16 02:12

RostSunshine


People also ask

What does ArrayList add return in Java?

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.

What is return type of add method in ArrayList?

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.

How does add in ArrayList work?

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.

What does Boolean return in Java?

A Boolean expression is a Java expression that returns a Boolean value: true or false .


2 Answers

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.

like image 79
Jack Avatar answered Oct 03 '22 19:10

Jack


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.

like image 43
Elliott Frisch Avatar answered Oct 03 '22 17:10

Elliott Frisch