我需要向ArrayList队列添加元素,但当我调用函数添加一个元素时,我希望它在数组的开头添加元素(因此它有最低的索引),如果数组有10个元素,添加一个新的结果是删除最古老的元素(具有最高索引的元素)。
有人有什么建议吗?
我需要向ArrayList队列添加元素,但当我调用函数添加一个元素时,我希望它在数组的开头添加元素(因此它有最低的索引),如果数组有10个元素,添加一个新的结果是删除最古老的元素(具有最高索引的元素)。
有人有什么建议吗?
当前回答
举个例子:-
List<String> element1 = new ArrayList<>();
element1.add("two");
element1.add("three");
List<String> element2 = new ArrayList<>();
element2.add("one");
element2.addAll(element1);
其他回答
您可以使用此代码
private List myList = new ArrayList();
private void addItemToList(Object obj){
if(myList.size()<10){
myList.add(0,obj);
}else{
myList.add(0,obj);
myList.remove(10);
}
}
带FIFO规则的有界循环缓冲区
看来您需要一个容量有限的循环缓冲区。 您更喜欢类似数组的行为,而不喜欢链接队列。 我说的对吗? 您似乎需要将容量设置为“10”。 这可以通过有界结构实现。 你似乎也需要一个先进先出的纪律。
使用ArrayBlockingQueue的解决方案
一个由数组支持的有界阻塞队列…排序元素FIFO(先进先出)。队列的头是在队列上停留时间最长的元素。队列的尾部是在队列上停留时间最短的元素。在队列尾部插入新元素,队列检索操作获取队列头部的元素。 放,拿都挡。提议,投票不阻拦。
PriorityBlockingQueue
你可以看看PriorityBlockingQueue的文档。有一个类的例子,它“对可比元素应用先进先出的绑定打破”。
ArrayBlockingQueue的示例
ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
for (int i = 10; i < 30; i++) {
if (queue.remainingCapacity() > 0) {
queue.offer(i);
} else {
queue.poll();
queue.offer(i);
}
if (queue.size() > 9) {
System.out.println(queue);
}
}
List有add(int, E)方法,所以你可以使用:
list.add(0, yourObject);
然后你可以删除最后一个元素:
if(list.size() > 10)
list.remove(list.size() - 1);
但是,您可能需要重新考虑您的需求或使用不同的数据结构,如Queue
EDIT
也许可以看看Apache的CircularFifoQueue:
CircularFifoQueue是一个先进先出队列,具有固定大小,如果已满则替换其最老的元素。
用你的最大大小初始化它:
CircularFifoQueue queue = new CircularFifoQueue(10);
你可以看一下add(int index, E element):
将指定元素插入到此列表中的指定位置。 移动当前位于该位置(如果有)的元素 右边的后续元素(给它们的下标加1)。
一旦你添加了数组列表,你就可以检查数组列表的大小,并删除末尾的数组列表。
import com.google.common.collect.Lists;
import java.util.List;
/**
* @author Ciccotta Andrea on 06/11/2020.
*/
public class CollectionUtils {
/**
* It models the prepend O(1), used against the common append/add O(n)
* @param head first element of the list
* @param body rest of the elements of the list
* @return new list (with different memory-reference) made by [head, ...body]
*/
public static <E> List<Object> prepend(final E head, List<E> final body){
return Lists.asList(head, body.toArray());
}
/**
* it models the typed version of prepend(E head, List<E> body)
* @param type the array into which the elements of this list are to be stored
*/
public static <E> List<E> prepend(final E head, List<E> body, final E[] type){
return Lists.asList(head, body.toArray(type));
}
}