Java ArrayList如何在开头添加元素 [英] Java ArrayList how to add elements at the beginning
问题描述
无论如何我都需要向ArrayList
队列中添加元素,但是当我调用函数添加元素时,我希望它在数组的开头添加元素(因此它具有最低的索引),如果该数组有10个元素,添加了一个新结果,即删除了最早的元素(索引最高的元素).
I need to add elements to an ArrayList
queue whatever, but when I call the function to add an element, I want it to add the element at the beginning of the array (so it has the lowest index) and if the array has 10 elements adding a new results in deleting the oldest element (the one with the highest index).
有人有什么建议吗?
推荐答案
List
has the method add(int, E)
, so you can use:
list.add(0, yourObject);
之后,您可以使用以下命令删除最后一个元素:
Afterwards you can delete the last element with:
if(list.size() > 10)
list.remove(list.size() - 1);
However, you might want to rethink your requirements or use a different data structure, like a Queue
编辑
也许看看Apache的 CircularFifoQueue
:
Maybe have a look at Apache's CircularFifoQueue
:
CircularFifoQueue
是大小固定的先进先出队列,如果已满,它将替换其最早的元素.
CircularFifoQueue
is a first-in first-out queue with a fixed size that replaces its oldest element if full.
只需使用您的最大大小对其进行初始化:
Just initialize it with you maximum size:
CircularFifoQueue queue = new CircularFifoQueue(10);
这篇关于Java ArrayList如何在开头添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!