ArrayList - Delete an element at a specific position in Java
The Method remove(int index) is used to remove an item from a specific position in the list.public Object remove(int index): this method returns the object if it has been successfully deleted, otherwise, it throws an exception IndexOutOfBoundException If the specified index is less than 0 or greater than the size of the ArrayList.
import java.util.ArrayList.Output:
public class removeArrayListIndex{
public static void main(String[] args) {
// Create an ArrayList< String>
ArrayList< String> aList = new ArrayList< String> ();
//add strings to ArrayList
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("5");
System.out.println("ArrayList before deletion:");
for(String e:aList)
System.out.println(e);
//delete object at 1
aList.remove(1);
System.out.println("ArrayList after deletion:");
for(String e:aList)
System.out.println(e);
//delete the object at the 3
aList.remove(3);
System.out.println("ArrayList after deletion:");
for(String e:aList)
System.out.println(e);
}
}
ArrayList before removal:
1
2
3
4
5
ArrayList after deletion:
1
3
4
5
ArrayList after deletion:
1
3
4