Java LinkedList – Why Does the add() Method Return True?

apijava

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?

Best Answer

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

Related Topic