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

有人有什么建议吗?


当前回答

使用特定的数据结构

有各种各样的数据结构经过优化,可以在第一个索引处添加元素。请注意,如果您将您的集合转换为其中之一,对话可能需要O(n)的时间和空间复杂度

甲板

JDK包括Deque结构,它提供了像addFirst(e)和offerFirst(e)这样的方法。

Deque<String> deque = new LinkedList<>();
deque.add("two");
deque.add("one");
deque.addFirst("three");
//prints "three", "two", "one"

分析

插入的空间复杂度和时间复杂度为LinkedList常量(O(1))。参见Big-O备忘单。

反转列表

一个非常简单但效率很低的方法是使用reverse:

 Collections.reverse(list);
 list.add(elementForTop);
 Collections.reverse(list);

如果您使用Java 8流,这个答案可能会让您感兴趣。

分析

时间复杂度:O(n) 空间复杂度:O(1)

看看JDK的实现,它的时间复杂度是O(n),所以只适用于非常小的列表。

其他回答

带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(lowestIndex, element);
list.remove(highestIndex, element);

我遇到了类似的问题,试图在现有数组的开头添加一个元素,将现有元素向右移动,并丢弃最古老的元素(数组[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

祝你好运

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

Java LinkedList提供了addFirst(E E)和push(E E)方法,用于将元素添加到列表前面。

https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html addFirst (E)