700888. Java ArrayList Operation
arraylist-operation
Summary
This problem involves working with ArrayList in Java, specifically inserting and removing elements. The task is to demonstrate how to efficiently perform these operations while maintaining the integrity of the data structure.
Detailed Explanation
The challenge is to create a program that inserts and removes elements from an ArrayList in Java. To do this, we can start by creating an instance of the ArrayList class and initializing it with some sample data. We'll then implement methods for inserting an element at a specific position and removing an element at a given index.
Here's a step-by-step breakdown of the solution:
-
Create an instance of the ArrayList class:
ArrayList<Integer> list = new ArrayList<>(); -
Initialize the list with some sample data:
list.add(10); list.add(20); list.add(30); -
Implement a method to insert an element at a specific position:
public void insert(int index, int val) { list.add(index, val); }- This method takes two parameters: the index where you want to insert the new element and the value of the new element itself.
- We use the
addmethod provided by the ArrayList class to add the new element at the specified position.
-
Implement a method to remove an element at a given index:
public void remove(int index) { list.remove(index); }- This method takes one parameter: the index of the element you want to remove.
- We use the
removemethod provided by the ArrayList class to remove the element at the specified position.
Time complexity for both operations is O(n), where n is the number of elements in the list. Space complexity is O(1) since we're not using any extra space that scales with the input size.
Optimized Solutions
Java
public class ArrayListOperation {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
list.add(30);
insert(list, 1, 25);
remove(list, 0);
for (int i : list) {
System.out.println(i);
}
}
public static void insert(ArrayList<Integer> list, int index, int val) {
list.add(index, val);
}
public static void remove(ArrayList<Integer> list, int index) {
list.remove(index);
}
}