Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

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
1  
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

2 Answers 2

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
1  
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

 
discard

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.