6

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

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html#add(E)

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?

3
  • public void add(int index, E element) - I don't see a return type there.
    – ChrisF
    Commented May 7, 2012 at 21:40
  • 1
    The other add method with a slightly different signature. Also, why do the signatures differ between these two overloaded functions?
    – David Faux
    Commented May 7, 2012 at 21:41
  • @DavidFaux because one is also implemented by Sets, and one is specific to Lists. Commented Dec 7, 2014 at 2:39

2 Answers 2

12

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.)...

1
  • 1
    Ah, add must return true to indicate that the element was successfully added (which collections must do). Thanks!
    – David Faux
    Commented May 7, 2012 at 23:34
2

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()));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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