Java数组如何在开始添加元素 [英] Java Arrays how to add elements at the beginning

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

问题描述

一个问题。

我需要的元素添加到什么,但是当我调用该函数添加我希望它在数组的开头添加元素的元素(所以它具有最低的指数),如果阵列有一个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).

任何快速code?

推荐答案

列表有方法的<$c$c>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);

但是,您可能要重新考虑你的要求,或者使用不同的数据结构,就像一个的 队列

修改

也许看看Apache的<一个href=\"https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.1/org/apache/commons/collections/buffer/CircularFifoBuffer.html\"><$c$c>CircularFifoBuffer:

Maybe have a look at Apache's CircularFifoBuffer:

CircularFifoBuffer是先出缓冲器的第一与一个固定的大小,如果充分,取代它的最旧的元素

CircularFifoBuffer is a first in first out buffer with a fixed size that replaces its oldest element if full.

只是你最大尺寸初始化:

Just initialize it with you maximum size:

Buffer buffer = new CircularFifoBuffer(10);

NB :共同的集合4, CircularFifoBuffer 现在<一个href=\"https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/queue/CircularFifoQueue.html\"><$c$c>CircularFifoQueue

NB: As of Common-Collections 4, CircularFifoBuffer is now CircularFifoQueue

这篇关于Java数组如何在开始添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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