Working with Arrays
1. Declaring and Creating Arrays
| Syntax | Example |
|---|---|
| Declaration | int[] nums; or int nums[]; |
| Allocation | int[] nums = new int[10]; |
| Combined init | int[] nums = {1, 2, 3}; |
| Anonymous array | method(new int[]{1,2,3}); |
2. Initializing Arrays
Example: Initialization
int[] zeros = new int[5]; // [0,0,0,0,0]
int[] vals = {10, 20, 30};
String[] names = new String[]{"A", "B"};
int[] filled = new int[5];
Arrays.fill(filled, 7); // [7,7,7,7,7]
int[] range = IntStream.rangeClosed(1, 5).toArray();
| Method | Result |
|---|---|
new int[n] | All zeros |
Arrays.fill(arr, val) | Fill all |
Arrays.setAll(arr, i -> expr) | Compute by index |
3. Accessing Array Elements
| Operation | Syntax |
|---|---|
| Read | arr[i] |
| Write | arr[i] = value; |
| Length | arr.length (no parentheses) |
| Bounds | 0 to length-1; otherwise ArrayIndexOutOfBoundsException |
4. Working with Multidimensional Arrays
Example: 2D and jagged
int[][] grid = new int[3][4];
int[][] matrix = {{1,2,3},{4,5,6}};
int[][] jagged = new int[3][];
jagged[0] = new int[]{1};
jagged[1] = new int[]{1,2};
jagged[2] = new int[]{1,2,3};
| Form | Notes |
|---|---|
| Rectangular | new int[r][c] |
| Jagged | new int[r][] then assign rows |
| Access | matrix[row][col] |
5. Understanding Array Length
| Item | Detail |
|---|---|
| Field | arr.length (final, public) |
| Immutable size | Fixed after creation |
| 2D rows | matrix.length |
| 2D cols (per row) | matrix[i].length |
6. Iterating Arrays
Example: Iteration patterns
for (int i = 0; i < arr.length; i++) sum += arr[i];
for (int v : arr) sum += v; // index not available
Arrays.stream(arr).forEach(System.out::println);
IntStream.range(0, arr.length).forEach(i -> ...);
| Pattern | When |
|---|---|
| Index loop | Need index or modify |
| For-each | Read only |
| Stream | Functional ops |
7. Copying Arrays
| Method | Use |
|---|---|
arr.clone() | Shallow copy |
Arrays.copyOf(arr, n) | Resize |
Arrays.copyOfRange(arr, from, to) | Sub-array (exclusive end) |
System.arraycopy(src, sPos, dst, dPos, len) | Fastest, manual |
8. Sorting Arrays
| Method | Use |
|---|---|
Arrays.sort(arr) | Natural order, dual-pivot quicksort |
Arrays.sort(arr, cmp) | Object array, comparator |
Arrays.sort(arr, from, to) | Range sort |
Arrays.parallelSort(arr) | Parallel for large arrays |
9. Searching Arrays
| Method | Notes |
|---|---|
Arrays.binarySearch(arr, key) | Array MUST be sorted; returns index or -(insertionPoint)-1 |
| Linear scan | For unsorted arrays, use a loop or stream .filter().findFirst() |
10. Comparing Arrays
| Method | Behavior |
|---|---|
Arrays.equals(a, b) | Element-wise (1D) |
Arrays.deepEquals(a, b) | Multi-dimensional |
Arrays.compare(a, b) | Lexicographic ordering (Java 9+) |
Arrays.mismatch(a, b) | Index of first difference (Java 9+) |
a == b | Reference equality only — DON'T use |
11. Converting Arrays
| Conversion | Method |
|---|---|
| Array → List | Arrays.asList(arr) (fixed size) |
| Array → Stream | Arrays.stream(arr) |
| Stream → Array | stream.toArray(String[]::new) |
| Array → String | Arrays.toString(arr) / deepToString |
| List → Array | list.toArray(new String[0]) |
12. Working with Varargs (...args)
Example: Varargs method
static int sum(int... nums) {
int total = 0;
for (int n : nums) total += n;
return total;
}
sum(); // 0
sum(1, 2, 3); // 6
sum(new int[]{1,2,3}); // 6
| Rule | Detail |
|---|---|
| Position | Must be the LAST parameter |
| Implementation | Treated as array inside method |
| Annotation | @SafeVarargs for generic varargs |