Java 中的后进后出
我有 90 个 ID,我需要如下图所示的内容。我希望首先弹出最后一个 ID,如果有新的 ID 添加到堆栈中,我想将它们推到堆栈的末尾。后进后出。这样的东西已经存在了吗?我知道我可以使用其他集合实现,但我想知道是否已经有这样的堆栈。
I have 90 IDs that I need to something like on the image below. I want the last ID to be popped first and if there are new IDs added to the stack I want to push them on the end of it. Last In Last Out. Does something like this exists already? I know I could use other collection implementations but I wonder if there is a stack like this already made.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
Queue 是一个具有多种实现的接口(包括例如适合多线程解决方案的阻塞队列)
Queue is an interface with multiple implementations (including such things as blocking queues suitable for multi-threaded solutions)
您可能想要一个
FIFO(先进先出)
队列。首先查看 java.util.Queue< 中的 Javadoc /a>.
存在多种实现:
You probably want to have a
FIFO (first-in-first-out)
queue.First have a look at Javadoc from java.util.Queue.
There exist several implementations:
您可以使用
Queue
。
You could use a
Queue<E>
.看起来像一个普通的队列实现,元素以相反的顺序添加到队列中。
looks like a normal queue implementation, with the elements added to the queue in reverse order to start off with.
您可以使用 java 提供的某种
Queue
实现(请参阅 队列 实现)。另一种可能的选择是使用
LinkedList
(参见:http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedList.html)它提供了您需要的所有方法。特别是因为如果您不完全确定自己想要的行为,那么您的描述似乎就是如此。
至少对于不需要随机访问的大型集合来说,
Queue
应该优先于LinkedList
。You may use sort of a
Queue<E>
implementation which is provided by java (see queue implementations).Another possible Option would be to use a
LinkedList<E>
(see.: http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedList.html)It offers all methods you need. Especially because your description seems so if you are not totally sure about the behavior you want.
A
Queue<E>
should be preferred over aLinkedList<E>
at least for large collections without the need of random access.下面是一些可以帮助您入门的代码:
Here's some code to get you started: