Junior
How does adding or removing elements in an array and list occur?
sobes.tech AI
Answer from AI
In a fixed-size array, removing/adding elements directly is impossible without creating a new array. When "removing," the element is usually marked as deleted or replaced with a special value, and the array size remains unchanged. When "adding," a new larger array must be created, old elements copied into it, and the new element added.
In dynamic lists (such as ArrayList in Java or list in Python), removing and adding elements is easier:
- Removing: An element is removed by index or value. Elements following the removed one are shifted to fill the gap. The list size decreases.
- Adding: An element is added at the end of the list or at a specific index. If the list reaches maximum capacity, a new internal array of larger size is created, old elements are copied into it, and then the new element is added. Elements after the insertion point are shifted. The list size increases.
Here is an example of adding and removing in Python:
# Creating a list
my_list = [1, 2, 3, 4, 5]
# Adding an element to the end
my_list.append(6)
# print(my_list) # [1, 2, 3, 4, 5, 6]
# Adding an element at an index
my_list.insert(2, 99)
# print(my_list) # [1, 2, 99, 3, 4, 5, 6]
# Removing an element by value
my_list.remove(3)
# print(my_list) # [1, 2, 99, 4, 5, 6]
# Removing an element by index
del my_list[1]
# print(my_list) # [1, 99, 4, 5, 6]
In Java, it looks like this:
import java.util.ArrayList;
// Creating a list
ArrayList<Integer> my_list = new ArrayList<>();
my_list.add(1);
my_list.add(2);
my_list.add(3);
my_list.add(4);
my_list.add(5);
// Adding an element to the end
my_list.add(6);
// System.out.println(my_list); // [1, 2, 3, 4, 5, 6]
// Adding an element at an index
my_list.add(2, 99);
// System.out.println(my_list); // [1, 2, 99, 3, 4, 5, 6]
// Removing an element by value
my_list.remove(Integer.valueOf(3));
// System.out.println(my_list); // [1, 2, 99, 4, 5, 6]
// Removing an element by index
my_list.remove(1);
// System.out.println(my_list); // [1, 99, 4, 5, 6]