Java Queue 中的 add 和 Offer 方法有什么区别?

发布于 2024-08-30 06:34:41 字数 1113 浏览 3 评论 0原文

PriorityQueue 为例 http://java.sun.com/j2se/1.5.0/docs/api/java/util/PriorityQueue.html#offer(E)

谁能给我一个例子队列 其中添加offer方法有什么不同?

根据集合 doc,add 方法通常会寻求确保元素存在于 Collection 中,而不是添加重复项。所以我的问题是,addoffer 方法有什么区别?

offer 方法是否会添加重复项? (我怀疑这是因为如果 Collection 应该只包含不同的元素,这就会规避这一点)。

编辑: 在 PriorityQueue 中,addoffer 方法是相同的方法(请参阅下面的我的答案)。谁能给我一个 addoffer 方法不同的类的示例?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

没有心的人 2024-09-06 06:35:02
  • 在Java中,Queue接口提供了两种添加元素的方法
    到队列:add(E e)offer(E e)

如果可以立即执行此操作而不违反容量限制,这两种方法都会将指定元素添加到队列中。但是,行为上有所不同:

add(E e):如果由于容量限制此时无法添加元素,则此方法会抛出 IllegalStateException

offer(E e):如果由于容量限制无法添加元素,该方法返回false,否则添加元素并返回true

下面是一个小例子来说明差异:

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {
    public static void main(String[] args) {
        Queue<Integer> queue = new LinkedList<>();
        int capacity = 2; // Set capacity to 2

    // add elements 1 to 3 to the queue
    for (int i = 1; i <= 3; i++) {
        // add() method
        if (queue.size() < capacity) {
            System.out.println("Adding " + i + " using add(): " + queue.add(i));
        } else {
            System.out.println("Capacity reached. Cannot add " + i + " using add()");
        }

        // offer() method
        System.out.println("Adding " + i + " using offer(): " + queue.offer(i));
    }
}

输出:

Adding 1 using add(): true
Adding 1 using offer(): true
Adding 2 using add(): true
Adding 2 using offer(): true
Capacity reached. Cannot add 3 using add()
Adding 3 using offer(): false
  • 此代码使用 LinkedList 创建一个容量为 2 的队列,并
    将元素 1 到 3 添加到队列中。
  • 它显示了添加和提供方法之间的区别
    队列达到其容量。
  • 当超出容量时,add()方法抛出异常
    offer() 方法在这种情况下返回 false
  • In Java, the Queue interface provides two methods for adding elements
    to the queue: add(E e) and offer(E e).

Both methods add the specified element to the queue if it is possible to do so immediately without violating capacity restrictions. However, there is a difference in behavior:

add(E e): This method throws an IllegalStateException if the element cannot be added at this time due to capacity restrictions.

offer(E e): This method returns false if the element cannot be added due to capacity restrictions, otherwise it adds the element and returns true.

Here's a small example to illustrate the difference:

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {
    public static void main(String[] args) {
        Queue<Integer> queue = new LinkedList<>();
        int capacity = 2; // Set capacity to 2

    // add elements 1 to 3 to the queue
    for (int i = 1; i <= 3; i++) {
        // add() method
        if (queue.size() < capacity) {
            System.out.println("Adding " + i + " using add(): " + queue.add(i));
        } else {
            System.out.println("Capacity reached. Cannot add " + i + " using add()");
        }

        // offer() method
        System.out.println("Adding " + i + " using offer(): " + queue.offer(i));
    }
}

Output :

Adding 1 using add(): true
Adding 1 using offer(): true
Adding 2 using add(): true
Adding 2 using offer(): true
Capacity reached. Cannot add 3 using add()
Adding 3 using offer(): false
  • This code creates a Queue with a capacity of 2 using a LinkedList and
    adds elements 1 to 3 to the queue.
  • It shows the difference between the add and offer methods when
    the queue reaches its capacity.
  • The add() method throws an exception when the capacity is exceeded,
    while the offer() method returns false in such cases.
久伴你 2024-09-06 06:34:59

如果添加完成,offer 方法抛出 true 或 false

add 方法在队列中无法添加时抛出异常

offer method throws true or false, if addition is done

add method throws an exception when no addition possible in queue

墨落成白 2024-09-06 06:34:58

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

Offer 方法会在可能的情况下插入一个元素,否则返回 false。这与 Collection.add 方法不同,后者只能通过抛出未经检查的异常来添加元素失败。 Offer 方法设计用于当故障是正常现象而不是异常情况时使用,例如在固定容量(或“有界”)队列中。

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.

坏尐絯℡ 2024-09-06 06:34:56

从jdk 7中的源代码中

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

我们可以很容易地知道,add函数在向队列中添加新元素成功时会返回true,而在失败时会抛出异常。

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 .

小帐篷 2024-09-06 06:34:55

我将为 offer 方法和 add 方法编写 java 合约示例代码,展示它们的不同之处。

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

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
倾听心声的旋律 2024-09-06 06:34:54

Queue 接口指定,如果当前没有可用空间,add() 将抛出 IllegalStateException(否则返回 true) 而如果由于容量限制而无法插入元素,offer() 将返回 false

它们在 PriorityQueue 中相同的原因是该队列被指定为无界的,即没有容量限制。在没有容量限制的情况下,add()offer() 合约显示相同的行为。

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.

睫毛上残留的泪 2024-09-06 06:34:53

javadoc 中的以下两个摘录解释了 offeradd 之间的区别:

来自 集合接口:

如果集合由于除已包含该元素以外的任何原因拒绝添加特定元素,则它必须抛出异常(而不是返回 false)。这保留了调用返回后集合始终包含指定元素的不变量。

来自 队列 接口

当使用可能施加插入限制(例如容量限制)的队列时,方法 offer 通常优于方法 Collection.add(E),后者可能会失败仅通过抛出异常来插入元素。

PriorityQueue 是一个 Queue 实现,它不施加任何插入限制。因此,addoffer 方法具有相同的语义。

相比之下,ArrayBlockingQueue 是一种实现,其中 offeradd 的行为有所不同,具体取决于队列的实例化方式。

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.

虫児飞 2024-09-06 06:34:52

区别如下:

  • offer 方法 - 尝试将元素添加到队列中,如果元素无法添加,则返回 false被添加(例如队列已满的情况),或者 true 如果元素已添加,并且不会抛出任何特定异常。

  • add 方法 - 尝试将元素添加到队列中,如果添加了元素,则返回 true;如果没有添加,则抛出 IllegalStateException空间当前可用。

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.

别把无礼当个性 2024-09-06 06:34:51

简短的回答:这取决于具体实施。

如果您的队列有最大容量限制,则实际上存在差异。

  • 应用案例 #1(无最大容量限制):

PriorityQueue

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

  • 应用案例#2(最大容量限制) :

实际上存在差异,例如 ArrayBlockingQueue 扩展了 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:如果队列已满,则返回 false 并且将不抛出异常
  • add:如果队列已满,则抛出异常

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
一萌ing 2024-09-06 06:34:50

我想区别在于合同,当元素无法添加到集合中时,add 方法会抛出异常,而 offer 则不会。

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

如果集合拒绝添加
出于任何原因的特定元素
除此之外它已经包含
元素,它必须抛出
异常(而不是返回
错误的)。这保留了不变性
集合总是包含
此调用后的指定元素
返回。

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

将指定元素插入到
如果可能的话,这个队列。使用时
可能强制插入的队列
限制(例如容量
边界),方法提供一般是
优于方法
Collection.add(E),可能会失败
仅通过抛出一个元素来插入一个元素
异常。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文