我需要向ArrayList队列添加元素,但当我调用函数添加一个元素时,我希望它在数组的开头添加元素(因此它有最低的索引),如果数组有10个元素,添加一个新的结果是删除最古老的元素(具有最高索引的元素)。
有人有什么建议吗?
我需要向ArrayList队列添加元素,但当我调用函数添加一个元素时,我希望它在数组的开头添加元素(因此它有最低的索引),如果数组有10个元素,添加一个新的结果是删除最古老的元素(具有最高索引的元素)。
有人有什么建议吗?
当前回答
你可能想看看Deque。它使您可以直接访问列表中的第一个和最后一个项。
其他回答
你可能想看看Deque。它使您可以直接访问列表中的第一个和最后一个项。
你可以使用
public List<E> addToListStart(List<E> list, E obj){
list.add(0,obj);
return (List<E>)list;
}
使用数据类型更改E
如果需要删除最老的元素,则可以添加:
list.remove(list.size()-1);
在return语句之前。否则list将在开始时添加对象并保留最古老的元素。
这将删除列表中的最后一个元素。
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);
}
}
你可以看一下add(int index, E element):
将指定元素插入到此列表中的指定位置。 移动当前位于该位置(如果有)的元素 右边的后续元素(给它们的下标加1)。
一旦你添加了数组列表,你就可以检查数组列表的大小,并删除末尾的数组列表。
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));
}
}