Java ArrayList 如何在开头添加元素 [英] Java ArrayList how to add elements at the beginning

查看:64
本文介绍了Java ArrayList 如何在开头添加元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将元素添加到 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 有方法 add(int, E),所以你可以使用:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆