java - Remove all elements from a List after a particular index - Stack Overflow
How does an ArrayList remove an element from an array?
java - Remove Item from ArrayList - Stack Overflow
Removing an item from an array list
Videos
list.subList(4, list.size()).clear();
Sublist operations are reflected in the original list, so this clears everything from index 4 inclusive to list.size() exclusive, a.k.a. everything after index 3. Range removal is specifically used as an example in the documentation:
This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a list can be used as a range operation by passing a subList view instead of a whole list. For example, the following idiom removes a range of elements from a list:
list.subList(from, to).clear();
Using sublist() and clear(),
public class Count
{
public static void main(String[] args)
{
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5");
arrayList.subList(2, arrayList.size()).clear();
System.out.println(arrayList.size());
}
}
Is it as simple as creating another array and moving all of the elements except the one to be deleted over?
In this specific case, you should remove the elements in descending order. First index 5, then 3, then 1. This will remove the elements from the list without undesirable side effects.
for (int j = i.length-1; j >= 0; j--) {
list.remove(i[j]);
}
You can remove elements from ArrayList using ListIterator,
ListIterator listIterator = List_Of_Array.listIterator();
/* Use void remove() method of ListIterator to remove an element from List.
It removes the last element returned by next or previous methods.
*/
listIterator.next();
//remove element returned by last next method
listIterator.remove();//remove element at 1st position
listIterator.next();
listIterator.next();
listIterator.remove();//remove element at 3rd position
listIterator.next();
listIterator.next();
listIterator.remove();//remove element at 5th position