Sobes.tech
Junior — Middle

How can a new element be inserted into the central part of an ArrayList?

sobes.tech AI

Answer from AI

To insert a new element into the middle of an ArrayList, you can use the add(int index, E element) method, specifying the index corresponding to the middle of the list. For example:

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("A");
        list.add("B");
        list.add("C");
        
        int middleIndex = list.size() / 2;
        list.add(middleIndex, "X");
        
        System.out.println(list); // Outputs [A, X, B, C]
    }
}

This will insert the element "X" into the middle of the list, shifting subsequent elements to the right.

How can a new element be inserted into the central… - sobes.tech