To insert an element at a specific index in a list in Java, you can use the add
method of the List
interface.
In this example,
numbers
with initial integer values.add
method to insert a new element at the desired index.add
method shifts the existing elements to the right to make space for the new element.import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
numbers.add(2, 10);
System.out.println("Updated list: " + numbers);
}
}
Updated list: [1, 2, 10, 3, 4, 5]
In this example,
numbers
with initial integer values.set
method to replace the element at the desired index with a new value.import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
numbers.set(2, 10);
System.out.println("Updated list: " + numbers);
}
}
Updated list: [1, 2, 10, 4, 5]
In this tutorial, we learned How to Insert an Element at Specific Index in a List in Java language with well detailed examples.