145

Take the PriorityQueue for example http://java.sun.com/j2se/1.5.0/docs/api/java/util/PriorityQueue.html#offer(E)

Can anyone give me an example of a Queue where the add and offer methods are different?

According to the Collection doc, the add method will often seek to ensure that an element exists within the Collection rather than adding duplicates. So my question is, what is the difference between the add and offer methods?

Is it that the offer method will add duplicates regardless? (I doubt that it is because if a Collection should only have distinct elements this would circumvent that).

EDIT: In a PriorityQueue the add and offer methods are the same method (see my answer below). Can anyone give me an example of a class where the add and offer methods are different?

Nikhil Arora
  • 329
  • 3
  • 9
Finbarr
  • 31,350
  • 13
  • 63
  • 94

9 Answers9

201

I guess the difference is in the contract, that when element can not be added to collection the add method throws an exception and offer doesn't.

From: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collection.html#add%28E%29

If a collection refuses to add a particular element for any reason other than that it already contains the element, it must throw an exception (rather than returning false). This preserves the invariant that a collection always contains the specified element after this call returns.

From: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Queue.html#offer%28E%29

Inserts the specified element into this queue, if possible. When using queues that may impose insertion restrictions (for example capacity bounds), method offer is generally preferable to method Collection.add(E), which can fail to insert an element only by throwing an exception.

Roy Hvaara
  • 139
  • 9
dvd
  • 2,296
  • 1
  • 15
  • 11
42

The short answer: it depends on the concrete implementation.

If your queue has a max capacity limit, there actually is a difference.

  • Case #1 (no max capacity limit) applied:

There is no difference like the implementation of PriorityQueue:

public boolean add(E e) {
    return offer(e);
}

  • Case #2 (max capacity limit) applied:

There actually is a difference like the implementation of ArrayBlockingQueue which extends AbstractQueue :

// ArrayBlockingQueue which extends AbstractQueue
public boolean add(E e) {
    return super.add(e);
}

// AbstractQueue
public boolean add(E e) {
    if (offer(e))
        return true;
    else
        throw new IllegalStateException("Queue full");
}
  • offer: if the queue is full, return false and will not throw an exception
  • add: if the queue is full, throw an exception
Ahmed Nabil
  • 17,392
  • 11
  • 61
  • 88
Peter Lang
  • 54,264
  • 27
  • 148
  • 161
  • I know, I just posted that answer myself a few minutes ago. Do you know of any classes where the `add` method is different to the `offer` method? – Finbarr Apr 24 '10 at 09:55
21

The difference is following:

  • offer method - tries to add an element to a queue, and returns false if the element can't be added (like in case when a queue is full), or true if the element was added, and doesn't throw any specific exception.

  • add method - tries to add an element to a queue, returns true if the element was added, or throws an IllegalStateException if no space is currently available.

  • 1
    add method never returns false if the element is already available Queue q = new PriorityQueue<>(); String b="java"; boolean is1 = q.add(b); boolean is2 = q.add("java"); boolean is3 = q.add(b); boolean is4 = q.offer("java"); boolean is5 = q.offer(b); boolean is6 = q.offer(b); System.out.println("qq::"+q); – Raj Nov 20 '18 at 12:15
  • Thanks, Raj! I've updated my response above. Oracle documentation says: "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." – Maksym Ovsianikov Nov 26 '18 at 08:49
20

The difference between offer and add is explained by these two excerpts from the javadocs:

From the Collection interface:

If a collection refuses to add a particular element for any reason other than that it already contains the element, it must throw an exception (rather than returning false). This preserves the invariant that a collection always contains the specified element after this call returns.

From the Queue interface

When using queues that may impose insertion restrictions (for example capacity bounds), method offer is generally preferable to method Collection.add(E), which can fail to insert an element only by throwing an exception.

PriorityQueue is a Queue implementation that does not impose any insertion restrictions. Therefore the add and offer methods have the same semantics.

By contrast, ArrayBlockingQueue is an implementation in which offer and add behave differently, depending on how the queue was instantiated.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
11

The Queue interface specifies that add() will throw an IllegalStateException if no space is currently available (and otherwise return true) while offer() will return false if the element couldn't be inserted due to capacity restrictions.

The reason they are the same in a PriorityQueue is that this queue is specified to be unbounded, i.e. there are no capacity restrictions. In the case of no capacity restrictions, the contracts of add() and offer() display the same behaviour.

Peter
  • 6,354
  • 1
  • 31
  • 29
8

from the source code in jdk 7 as follow:

public boolean add(E e) {
    if (offer(e))
        return true;
    else
        throw new IllegalStateException("Queue full");
}

we can easily know that the add function will return true when successfully add a new element into the queue, but throw a exception when failed .

Raging Bull
  • 18,593
  • 13
  • 50
  • 55
Heavin
  • 81
  • 1
  • 2
8

I will write the java contract example code for the offer method and the add method showing how they differ.

BlockingQueue<String> queue = new ArrayBlockingQueue<>(2);
queue.add("TestQuue1");  // will return true        
queue.add("TestQuue2");  // will return true
queue.add("TestQuue3");  // will throw "java.lang.IllegalStateException: Queue full

BlockingQueue<String> queue = new ArrayBlockingQueue<>(2);
queue.offer("TestQuue1"); // will return true       
queue.offer("TestQuue2"); // will return true   
queue.offer("TestQuue3"); // will return false and will not throw any exception
Ahmed Nabil
  • 17,392
  • 11
  • 61
  • 88
Aslam a
  • 750
  • 10
  • 19
1

Source: http://docs.oracle.com/javase/6/docs/api/java/util/Queue.html

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.

Yeshodhan Kulkarni
  • 2,844
  • 1
  • 16
  • 19
1

offer method throws true or false, if addition is done

add method throws an exception when no addition possible in queue

Neha Jain
  • 53
  • 6