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

有人有什么建议吗?


当前回答

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

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

其他回答

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

import java.util.*:
public class Logic {
  List<String> list = new ArrayList<String>();
  public static void main(String...args) {
  Scanner input = new Scanner(System.in);
    Logic obj = new Logic();
      for (int i=0;i<=20;i++) {
        String string = input.nextLine();
        obj.myLogic(string);
        obj.printList();
      }
 }
 public void myLogic(String strObj) {
   if (this.list.size()>=10) {
      this.list.remove(this.list.size()-1);
   } else {
     list.add(strObj); 
   }
 }
 public void printList() {
 System.out.print(this.list);
 }
}

您所描述的是使用Queue的合适情况。

因为你想添加新的元素,并删除旧的。你可以在结尾添加,也可以从开头删除。那不会有太大区别。

Queue有add(e)和remove()方法,它们分别在结尾添加新元素,并从开头删除旧元素。

Queue<Integer> queue = new LinkedList<Integer>();
queue.add(5);
queue.add(6);
queue.remove();  // Remove 5

因此,每次向队列添加元素时,都可以使用remove方法调用将其备份。


更新:

如果你想修复队列的大小,那么你可以看看:- ApacheCommons#CircularFifoBuffer

来自文档:-

CircularFifoBuffer是一个固定大小的先进先出缓冲区 如果已满,则替换最老的元素。

Buffer queue = new CircularFifoBuffer(2); // Max size

queue.add(5);
queue.add(6);
queue.add(7);  // Automatically removes the first element `5`

如您所见,当达到最大大小时,添加新元素将自动删除插入的第一个元素。

您可以使用此代码

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