首先,我找不到Stack数据结构的接口(interface)。它存在,但我发现它扩展了一个我会尽量避免使用的 Vector。因此,如果您确实需要一个堆栈,您会建议我实现自己的堆栈类(内部有一个 ArrayDeque),还是会建议我使用扩展 Vector 的 Stack 类?我非常失望 Java 中不存在一个好的 Stack 接口(interface)。
其次,Queue 提供了 add(e)、remove() 和 element() 方法。最重要的是,他们还提供了 Offer(e)、poll() 和 peek() 方法。前者抛出异常,后者返回 true 或 false 或 null。如果您要使用的队列用于非并发情况,您会使用哪一个?
最佳答案
回答您的第一个“问题”:Is there a drop-in replacement for Java Stack that is not synchronized?
<小时/>第二个问题:(我不想这么说,但是)RTFD。 说真的。
public interface Queue<E> extends Collection<E>
... Each of these methods exists in two forms: one throws an exception if the operation fails, the other returns a special value (either null or false, depending on the operation). The latter form of the insert operation is designed specifically for use with capacity-restricted Queue implementations; in most implementations, insert operations cannot fail.
http://download.oracle.com/javase/7/docs/api/java/util/Queue.html
这两组方法都与并发无关。它们只是允许您在两种编程风格之间进行选择(希望您保持一致!):您想要检查返回值还是捕获异常?
关于java - Java Collection API 中的不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8130919/