Array Manipulation Techniques
Core Array Manipulation Methods
1. Element Access and Modification
int[] numbers = {10, 20, 30, 40, 50};
// Accessing elements
int firstElement = numbers[0]; // 10
int lastElement = numbers[numbers.length - 1]; // 50
// Modifying elements
numbers[2] = 35; // Change third element
Iteration Techniques
Traditional For Loop
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Enhanced For Loop (For-Each)
for (int number : numbers) {
System.out.println(number);
}
Array Copying Methods
graph TD
A[Array Copying] --> B[System.arraycopy]
A --> C[Arrays.copyOf]
A --> D[Clone Method]
System.arraycopy
int[] source = {1, 2, 3, 4, 5};
int[] destination = new int[5];
System.arraycopy(source, 0, destination, 0, source.length);
Arrays.copyOf
import java.util.Arrays;
int[] original = {1, 2, 3, 4, 5};
int[] copied = Arrays.copyOf(original, original.length);
Sorting and Searching
Sorting Arrays
import java.util.Arrays;
int[] numbers = {5, 2, 9, 1, 7};
Arrays.sort(numbers); // Sorts in ascending order
Searching in Arrays
int[] numbers = {10, 20, 30, 40, 50};
int index = Arrays.binarySearch(numbers, 30); // Returns index 2
Advanced Manipulation Techniques
Filling Arrays
int[] filledArray = new int[5];
Arrays.fill(filledArray, 100); // Fills entire array with 100
Comparison Techniques
Operation |
Method |
Description |
Equality |
Arrays.equals() |
Compare two arrays |
Comparison |
Arrays.compare() |
Compare array elements |
Complete Example
import java.util.Arrays;
public class ArrayManipulationDemo {
public static void main(String[] args) {
int[] numbers = {45, 12, 78, 23, 56};
// Sorting
Arrays.sort(numbers);
// Printing sorted array
System.out.println("Sorted Array: " +
Arrays.toString(numbers));
// Searching
int searchResult = Arrays.binarySearch(numbers, 45);
System.out.println("Index of 45: " + searchResult);
// Copying
int[] copiedArray = Arrays.copyOf(numbers, numbers.length);
}
}
- Use appropriate iteration method
- Prefer
Arrays
utility methods
- Be cautious with large arrays
Best Practices
- Always check array bounds
- Use appropriate copying method
- Leverage built-in Java array utilities
LabEx recommends practicing these techniques to become proficient in array manipulation.