aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Difference between add() and offer() in Queue Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Difference between add() and offer() in Queue" Watch "Difference between add() and offer() in Queue" New topic
Author

Difference between add() and offer() in Queue

Satyajeet Kadam
Ranch Hand

Joined: Oct 19, 2006
Posts: 202
Q1) What is difference between add() and offer() in priorityQueue

As per both methods throw an ClassCastException if element that is to be added cannot be compared with elements already present in the Queue.

NullPointerException if the specified element is null.

I found the add() internally calls the offer()









Q2)why there are two methods for same operations
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

they are same. but the methods are used in different context.
Queue is a Collection. and offer() is in Queue. consider below code,
Satyajeet Kadam
Ranch Hand

Joined: Oct 19, 2006
Posts: 202
Can you please elaborate your answer?
Eduardo Mineo
Ranch Hand

Joined: Sep 26, 2011
Posts: 63

Satyajeet, you can see in SunOracle Queue specification:

The offer method inserts an element if possible, otherwise returning false. This differs from the Collection.add method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity (or "bounded") queues.


--eduardo
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Difference between add() and offer() in Queue
 
Similar Threads
java.util.Queue API design
doubt in priority queue in java 1.5
minheap and iterator
Iterator Pattern
Priority Queue