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 arra
You may want to look at Deque. it gives you direct access to both the first and last items in the list.
I think the implement should be easy, but considering about the efficiency, you should use LinkedList but not ArrayList as the container. You can refer to the following code:
import java.util.LinkedList;
import java.util.List;
public class DataContainer {
private List<Integer> list;
int length = 10;
public void addDataToArrayList(int data){
list.add(0, data);
if(list.size()>10){
list.remove(length);
}
}
public static void main(String[] args) {
DataContainer comp = new DataContainer();
comp.list = new LinkedList<Integer>();
int cycleCount = 100000000;
for(int i = 0; i < cycleCount; i ++){
comp.addDataToArrayList(i);
}
}
}
I had a similar problem, trying to add an element at the beginning of an existing array, shift the existing elements to the right and discard the oldest one (array[length-1]). My solution might not be very performant but it works for my purposes.
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
Good luck
you can use this code
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));
}
}
You can use list methods, remove and add
list.add(lowestIndex, element);
list.remove(highestIndex, element);