51

Why two functions for doing same thing?

Description provided in java api docs at http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html is same.

TheCrazyProgrammer
  • 7,918
  • 8
  • 25
  • 41
  • There is another thread on StackOverFlow with similar query : [Difference between add and offer method][1] [1]: http://stackoverflow.com/questions/2703984/what-is-the-difference-between-the-add-and-offer-methods-in-a-queue – Ankur Shanbhag Mar 23 '13 at 20:07

1 Answers1

114

The two functions come from two different interfaces that PriorityQueue implements:

  • add() comes from Collection.
  • offer() comes from Queue.

For a capacity-constrained queue, the difference is that add() always returns true and throws an exception if it can't add the element, whereas offer() is allowed to return false if it can't add the element.

However, this doesn't apply to PriorityQueue; the two functions are synonymous.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • What do mean by capacity constrained queue? – user7098526 Dec 05 '20 at 03:36
  • 2
    @user7098526 Some queue implementations may have fixed capacity, for e.g. ArrayBlockingQueue. The use case may be some buffer that will simply reject add request if it's full already - kinda a protection of OOO. – Mingliang Liu May 12 '21 at 05:14