Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Why does the add method of a Linkedlist return true in Java?

Why not just make it a void method? I know it says "per the general contract of Collection.add", but why doesn't this contract/interface make add a void method?

share|improve this question
public void add(int index, E element) - I don't see a return type there. – ChrisF May 7 '12 at 21:40
The other add method with a slightly different signature. Also, why do the signatures differ between these two overloaded functions? – David Faux May 7 '12 at 21:41
@DavidFaux because one is also implemented by Sets, and one is specific to Lists. – immibis Dec 7 '14 at 2:39
up vote 10 down vote accepted

This is to allow referencing to LinkedList instances as List or Collection.

boolean addSomething(Collection c) {
    return c.add(null); // expects collection, with add returning boolean

void hackList(LinkedList list) {
    addSomething(list); // list is a Collection, OK to pass

LinkedList is a List and Collection.

As for why a Collection would need to return boolean, this looks clearly explained in respective javadocs:

...Ensures that this collection contains the specified element (optional operation). Returns true if this collection changed as a result of the call. (Returns false if this collection does not permit duplicates and already contains the specified element.)...

share|improve this answer
Ah, add must return true to indicate that the element was successfully added (which collections must do). Thanks! – David Faux May 7 '12 at 23:34

In addition to the excellent answer gnat gave, it can be useful to know that you just tried to add null to a list, and therefore did not change it. While you could check for this separately, it's kinda nice to be able to say

if (myList.add(foo)) { doSomething(); }

or perhaps

while (myList.add(buffer.readLine()));
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.