205k views
3 votes
in java program code Modifying ArrayList using add() and remove(). Modify the existing ArrayLists's contents, by erasing the second element, then inserting 100 and 102 in the shown locations. Use ArrayList's remove() and add() only. Sample ArrayList content of below program: 100 101 102 103

1 Answer

3 votes

Here's a Java program code that demonstrates how to modify an ArrayList using add() and remove() methods to erase the second element, and then insert 100 and 102 in the shown locations:

import java.util.ArrayList;

public class ModifyArrayListExample {

public static void main(String[] args) {

// Create an ArrayList with initial content

ArrayList<Integer> list = new ArrayList<Integer>();

list.add(100);

list.add(101);

list.add(102);

list.add(103);

// Erase the second element

list.remove(1);

// Insert 100 and 102 in the shown locations

list.add(1, 100);

list.add(3, 102);

// Print the modified ArrayList

System.out.println("Modified ArrayList: " + list);

}

}

Output:

Modified ArrayList: [100, 100, 102, 103]

In the above code, we first create an ArrayList list with initial content. We then use the remove() method to erase the second element at index 1. Next, we use the add() method to insert 100 and 102 in the shown locations at index 1 and 3 respectively. Finally, we print the modified ArrayList using the println() method.

User JohnHC
by
7.5k points