List Modification Methods
Core Modification Operations
Adding Elements
public class ArrayBackedList<E> {
// Add element at the end
public void add(E element) {
ensureCapacity();
elements[size++] = element;
}
// Insert element at specific index
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacity();
System.arraycopy(elements, index,
elements, index + 1,
size - index);
elements[index] = element;
size++;
}
}
Removal Methods
public class ArrayBackedList<E> {
// Remove element by index
public E remove(int index) {
rangeCheck(index);
E oldValue = (E) elements[index];
int numMoved = size - index - 1;
if (numMoved > 0) {
System.arraycopy(elements, index + 1,
elements, index,
numMoved);
}
elements[--size] = null;
return oldValue;
}
// Remove first occurrence of element
public boolean remove(Object o) {
int index = indexOf(o);
if (index >= 0) {
remove(index);
return true;
}
return false;
}
}
Modification Operations Comparison
Operation |
Time Complexity |
Description |
Add (end) |
O(1) amortized |
Fastest insertion |
Add (index) |
O(n) |
Requires element shifting |
Remove (index) |
O(n) |
Requires element shifting |
Remove (object) |
O(n) |
Searches and shifts elements |
Modification Flow Visualization
graph TD
A[Modification Request] --> B{Type of Operation}
B --> |Add| C[Ensure Capacity]
B --> |Remove| D[Find Element]
C --> E[Insert Element]
D --> F[Shift Elements]
E --> G[Update Size]
F --> G
Best Practices in LabEx Development
- Always check array capacity before modifications
- Use
System.arraycopy()
for efficient element shifting
- Implement range checking to prevent index out of bounds
Advanced Modification Techniques
public class ArrayBackedList<E> {
// Bulk operations
public void addAll(Collection<? extends E> c) {
Object[] elements = c.toArray();
int numNew = elements.length;
ensureCapacity(size + numNew);
System.arraycopy(elements, 0,
this.elements, size,
numNew);
size += numNew;
}
// Clear entire list
public void clear() {
for (int i = 0; i < size; i++) {
elements[i] = null;
}
size = 0;
}
}
- Minimize unnecessary element shifting
- Use bulk operations when possible
- Implement lazy resizing strategies
- Preallocate capacity for known collection sizes