0

I'm looking through the Java 8 documentation for LinkedList, and I see several methods that appear to do the same thing. For example:

  1. add(E e): Appends the specified element to the end of this list.
  2. addLast(E e): Appends the specified element to the end of this list.
  3. offer(E e): Adds the specified element as the tail (last element) of this list.

These three appear to all do the same thing. I see that add and offer both return booleans signifying whether the modification was successful or not.

The docs for add even say it is the same as addLast, although it doesn't return anything. I guess I'm wondering why all this redundancy? When would I choose one over the other?

rocksNwaves
  • 5,331
  • 4
  • 38
  • 77

1 Answers1

8

LinkedList implements several interfaces:

  • add comes from the List and Queue interfaces, which get it from Collection;
  • offer comes from the Queue interface, and differs from the add method in terms of what it does on failure (described in a table in the Javadoc);
  • addLast comes from the Deque interface. Deque is also a Collection, and so has the add method; perhaps the addLast is there for clarity and symmetry with the addFirst method, so you're not left in any doubt as to which end add is adding to. As described in the Javadoc, Deque.addLast and Queue.add are equivalent.

In terms of which you should choose: pretty much up to you, since they do the same thing (give or take a return type).


The bigger question is: why does LinkedList try to be so many things (not very single-responsibility-principle, is it?); and should you be using that at all?

There's a thread on Twitter where Josh Bloch - the author of java.util.LinkedList - questions whether it is actually useful at all. He suggests that you are better off using ArrayList or ArrayDeque, depending on exactly what you need it to do.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243