To remove an element at a specific index from a list in Java, you can use the remove method.
In this example,
numbers
with integer values.remove
method of the ArrayList to remove the element at the specified index.import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
int indexToRemove = 2;
numbers.remove(indexToRemove);
System.out.println("ArrayList after removing element at index " + indexToRemove + ": " + numbers);
}
}
ArrayList after removing element at index 2: [1, 2, 4, 5]
In this example,
words
with string values.remove
method of the ArrayList to remove the element at the first index.import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> words = new ArrayList<>();
words.add("apple");
words.add("banana");
words.add("cherry");
words.remove(0);
System.out.println("ArrayList after removing element at first index: " + words);
}
}
ArrayList after removing element at first index: [banana, cherry]
In this tutorial, we learned How to Remove Element at a Specific Index from a List in Java language with well detailed examples.