consider I have an array list like : [2,5,1,8,6]
and I want to remove all elements from 1 till the end .and the arraylist will be like :[2,5]
how can i do this?
thanks
5 Answers
The most efficient way to remove elements from ArrayList is to remove them from the end of the list. Each element you remove from the middle of the list will result in all the latter elements being moved to the left. If the list is large, this can result in a significant performance issue.
However, in your case, you might be better off just creating a new sublist with the remaining two elements.
Comments
Another way of doing it would be to simply pop items off the end of the List until we have popped the starting element. Each item can be popped in O(1) time, so the entire operation is O(n).
class Main{
private static List<Integer> inputs = new ArrayList<Integer>();
public static void main(String args[]){
for (int x: new int[]{2,5,1,8,6})
inputs.add(x);
System.out.println(inputs);
int start=inputs.indexOf(1);
if (start>=0){ //check if there is a 1 in input
while (inputs.size()>start)
inputs.remove(inputs.size()-1);
}
System.out.println(inputs);
}
}