File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Difference between add() and addList() methods? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Difference between add() and addList() methods?" Watch "Difference between add() and addList() methods?" New topic

Difference between add() and addList() methods?

kenny gill
Ranch Hand

Joined: Mar 12, 2012
Posts: 54

I have no idea where to find the information for this question and could use some advice:

The API says that add(E e) and addLast(E e) are equivalent, but there is a difference. What is it?
Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42965
I'm guessing you're talking about the java.util.Deque interface. That would have been useful to mention, I had to hunt around the javadocs a bit to find which collection class/interface it might be :-)

If you have an object implementing Deque, then both methods will do the same. The difference is that using add will allow you to use an object that implements Queue instead, since add is part of both interfaces, whereas addLast is only part of Dequeue.

Why would you want to do this? Well, there may come a day when you decide that you didn't need to use a Deque after all, and would like to switch to Queue instead (maybe in order to use other collection classes that implement Queue, but not Deque). Had you used addLast, then you would need to refactor your code to use add instead; if you had used add from the beginning, then there is no need to change anything.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46368
Bear Bibeault wrote: . . . .

I have updated the subject for you -- please use it as a guide for future topics. Thanks.
Thank you, Bear. But I think you introduced a spectacular spelling error
Mansukhdeep Thind
Ranch Hand

Joined: Jul 27, 2010
Posts: 1157

BEWARE ALL!! Ma main man Ritchie is the mood for correcting everyone's grammar and composition today .

~ Mansukh
I agree. Here's the link:
subject: Difference between add() and addList() methods?
It's not a secret anymore!