我需要向ArrayList队列添加元素,但当我调用函数添加一个元素时,我希望它在数组的开头添加元素(因此它有最低的索引),如果数组有10个元素,添加一个新的结果是删除最古老的元素(具有最高索引的元素)。

有人有什么建议吗?


当前回答

您可以使用列表方法,删除和添加

list.add(lowestIndex, element);
list.remove(highestIndex, element);

其他回答

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));
    }
}

你可能想看看Deque。它使您可以直接访问列表中的第一个和最后一个项。

您可以使用此代码

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);
    }
}

我遇到了类似的问题,试图在现有数组的开头添加一个元素,将现有元素向右移动,并丢弃最古老的元素(数组[length-1])。 我的解决方案可能不是很高效,但它符合我的目的。

 Method:

   updateArray (Element to insert)

     - for all the elements of the Array
       - start from the end and replace with the one on the left; 
     - Array [0] <- Element

祝你好运

你可以看一下add(int index, E element):

将指定元素插入到此列表中的指定位置。 移动当前位于该位置(如果有)的元素 右边的后续元素(给它们的下标加1)。

一旦你添加了数组列表,你就可以检查数组列表的大小,并删除末尾的数组列表。