Practical Array Techniques
Advanced Array Manipulation Strategies
Array Copying Techniques
System.arraycopy()
public class ArrayCopyExample {
public static void main(String[] args) {
int[] original = {1, 2, 3, 4, 5};
int[] destination = new int[5];
// Full array copy
System.arraycopy(original, 0, destination, 0, original.length);
// Partial array copy
System.arraycopy(original, 1, destination, 0, 3);
}
}
Arrays.copyOf() Method
public class CopyOfExample {
public static void main(String[] args) {
int[] original = {1, 2, 3, 4, 5};
// Create a copy with same length
int[] copy = Arrays.copyOf(original, original.length);
// Create an expanded copy
int[] expandedCopy = Arrays.copyOf(original, 10);
}
}
Array Manipulation Operations
Sorting Techniques
public class SortingExample {
public static void main(String[] args) {
// Simple sorting
int[] numbers = {5, 2, 9, 1, 7};
Arrays.sort(numbers);
// Partial sorting
Arrays.sort(numbers, 1, 4);
// Custom object sorting
Person[] people = {new Person("Alice"), new Person("Bob")};
Arrays.sort(people, Comparator.comparing(Person::getName));
}
}
Search Techniques
Binary Search
public class SearchExample {
public static void main(String[] args) {
int[] sortedArray = {10, 20, 30, 40, 50};
// Standard binary search
int index = Arrays.binarySearch(sortedArray, 30);
// Partial array search
int partialIndex = Arrays.binarySearch(sortedArray, 1, 4, 30);
}
}
public class StreamTransformExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
// Map transformation
int[] squared = Arrays.stream(numbers)
.map(n -> n * n)
.toArray();
// Filter transformation
int[] evenNumbers = Arrays.stream(numbers)
.filter(n -> n % 2 == 0)
.toArray();
}
}
Multi-Dimensional Arrays
Creating and Manipulating 2D Arrays
public class MultiDimensionalExample {
public static void main(String[] args) {
// 2D array declaration
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Iterating 2D array
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}
}
Technique |
Time Complexity |
Space Complexity |
Arrays.sort() |
O(n log n) |
O(log n) |
System.arraycopy() |
O(n) |
O(n) |
Stream Transformations |
O(n) |
O(n) |
Visualization of Array Operations
graph TD
A[Array Operations] --> B[Copying]
A --> C[Sorting]
A --> D[Searching]
A --> E[Transforming]
Best Practices
- Use appropriate copying methods
- Prefer built-in methods for efficiency
- Consider memory implications
- Use streams for complex transformations
Conclusion
Mastering these practical array techniques will significantly enhance your Java programming skills and code efficiency.
Note: Explore more advanced techniques with LabEx to deepen your understanding.