Utilities
Arrays Utility Class
When processing data stored in arrays, you often need to sort, search, or compare them. The Arrays utility class provides optimized static methods for common array operations, eliminating the need to write these algorithms yourself.
Arrays class
A utility class in java.util providing static methods for array manipulation including sorting, searching, and copying.
Sorting Arrays
Sort arrays in place using optimized algorithms.
Sort.java
Replay: real traced execution (multi-file project)
// Arrays.sort examples
import java.util.Arrays;
public class Sort {
public static void main(String[] args) {
System.out.println("Sort integers:");
int[] nums = {5, 2, 8, 1, 9, 3};
System.out.println("Original: " + Arrays.toString(nums));
Arrays.sort(nums);
System.out.println("Sorted: " + Arrays.toString(nums));
System.out.println("\nSort range [1, 4):");
int[] nums2 = {5, 2, 8, 1, 9, 3};
System.out.println("Original: " + Arrays.toString(nums2));
Arrays.sort(nums2, 1, 4); // Sort indices 1-3
System.out.println("Sorted: " + Arrays.toString(nums2));
System.out.println("\nSort strings:");
String[] fruits = {"banana", "apple", "cherry", "date"};
System.out.println("Original: " + Arrays.toString(fruits));
Arrays.sort(fruits);
System.out.println("Sorted: " + Arrays.toString(fruits));
System.out.println("\nSort doubles:");
double[] prices = {19.99, 5.99, 12.50, 8.75, 15.00};
System.out.println("Original: " + Arrays.toString(prices));
Arrays.sort(prices);
System.out.println("Sorted: " + Arrays.toString(prices));
System.out.println("\nSort descending:");
Integer[] values = {5, 2, 8, 1, 9, 3};
System.out.println("Original: " + Arrays.toString(values));
Arrays.sort(values, (a, b) -> b - a); // Reverse order
System.out.println("Sorted: " + Arrays.toString(values));
System.out.println("\nSort strings by length:");
String[] words = {"cat", "elephant", "dog", "butterfly"};
System.out.println("Original: " + Arrays.toString(words));
Arrays.sort(words, (a, b) -> a.length() - b.length());
System.out.println("Sorted: " + Arrays.toString(words));
System.out.println("\nSort case-insensitive:");
String[] names = {"alice", "Bob", "CHARLIE", "david"};
System.out.println("Original: " + Arrays.toString(names));
Arrays.sort(names, String.CASE_INSENSITIVE_ORDER);
System.out.println("Sorted: " + Arrays.toString(names));
System.out.println("\nParallel sort (large array):");
int[] large = new int[1000];
for (int i = 0; i < large.length; i++) {
large[i] = large.length - i;
}
Arrays.parallelSort(large);
System.out.println("First 10: " + Arrays.toString(Arrays.copyOfRange(large, 0, 10)));
System.out.println("Last 10: " + Arrays.toString(Arrays.copyOfRange(large, 990, 1000)));
System.out.println("\nVerify sorted:");
int[] sorted = {1, 2, 3, 4, 5};
int[] unsorted = {1, 3, 2, 4, 5};
System.out.println("Is [1,2,3,4,5] sorted? " + isSorted(sorted));
System.out.println("Is [1,3,2,4,5] sorted? " + isSorted(unsorted));
}
static boolean isSorted(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) return false;
}
return true;
}
}
public static void main(String[] args)
5public class Sort {6 public static void main(String[] args) {7 System.out.println("Sort integers:");8 int[] nums = {5, 2, 8, 1, 9, 3};9 System.out.println("Original: " + Arrays.toString(nums));1011 Arrays.sort(nums);12 System.out.println("Sorted: " + Arrays.toString(nums));13 System.out.println("\nSort range [1, 4):");14 int[] nums2 = {5, 2, 8, 1, 9, 3};15 System.out.println("Original: " + Arrays.toString(nums2));1617 Arrays.sort(nums2, 1, 4); // Sort indices 1-318 System.out.println("Sorted: " + Arrays.toString(nums2));19 System.out.println("\nSort strings:");20 String[] fruits = {"banana", "apple", "cherry", "date"};21 System.out.println("Original: " + Arrays.toString(fruits));2223 Arrays.sort(fruits);24 System.out.println("Sorted: " + Arrays.toString(fruits));25 System.out.println("\nSort doubles:");26 double[] prices = {19.99, 5.99, 12.50, 8.75, 15.00};27 System.out.println("Original: " + Arrays.toString(prices));2829 Arrays.sort(prices);30 System.out.println("Sorted: " + Arrays.toString(prices));31 System.out.println("\nSort descending:");32 Integer[] values = {5, 2, 8, 1, 9, 3};33 System.out.println("Original: " + Arrays.toString(values));3435 Arrays.sort(values, (a, b) -> b - a); // Reverse order36 System.out.println("Sorted: " + Arrays.toString(values));37 System.out.println("\nSort strings by length:");38 String[] words = {"cat", "elephant", "dog", "butterfly"};39 System.out.println("Original: " + Arrays.toString(words));4041 Arrays.sort(words, (a, b) -> a.length() - b.length());42 System.out.println("Sorted: " + Arrays.toString(words));43 System.out.println("\nSort case-insensitive:");44 String[] names = {"alice", "Bob", "CHARLIE", "david"};45 System.out.println("Original: " + Arrays.toString(names));4647 Arrays.sort(names, String.CASE_INSENSITIVE_ORDER);48 System.out.println("Sorted: " + Arrays.toString(names));49 System.out.println("\nParallel sort (large array):");50 int[] large = new int[1000];51 for (int i = 0; i < large.length; i++) {outputSort integers: Original: [5, 2, 8, 1, 9, 3] Sorted: [1, 2, 3, 5, 8, 9] Sort range [1, 4): Original: [5, 2, 8, 1, 9, 3] Sorted: [5, 1, 2, 8, 9, 3] Sort strings: Original: [banana, apple, cherry, date] Sorted: [apple, banana, cherry, date] Sort doubles: Original: [19.99, 5.99, 12.5, 8.75, 15.0] Sorted: [5.99, 8.75, 12.5, 15.0, 19.99] Sort descending: Original: [5, 2, 8, 1, 9, 3] Sorted: [9, 8, 5, 3, 2, 1] Sort strings by length: Original: [cat, elephant, dog, butterfly] Sorted: [cat, dog, elephant, butterfly] Sort case-insensitive: Original: [alice, Bob, CHARLIE, david] Sorted: [alice, Bob, CHARLIE, david] Parallel sort (large array):large[i] ← 1000
pass 1 of 100050int[] large = new int[1000];51for (int i0 = 0; i < large.length1000; i++) {52 large[i]→ 1000 = large.length1000 - i0;53}1000 passes — pass 1 is the card above pass ilarge[i]1 0 0 → 1000 2 1 0 → 999 3 2 0 → 998 4 3 0 → 997 5 4 0 → 996 6 5 0 → 995 7 6 0 → 994 8 7 0 → 993 9 8 0 → 992 ⋯ 989 more passes ⋯ 999 998 0 → 2 1000 999 0 → 1 Arrays.parallelSort(large);
55Arrays.parallelSort(large);56System.out.println("First 10: " + Arrays.toString(Arrays.copyOfRange(large, 0, 10)));57System.out.println("Last 10: " + Arrays.toString(Arrays.copyOfRange(large, 990, 1000)));58System.out.println("\nVerify sorted:");59int[] sorted = {1, 2, 3, 4, 5};60int[] unsorted = {1, 3, 2, 4, 5};6162System.out.println("Is [1,2,3,4,5] sorted? " + isSorted(sorted));63System.out.println("Is [1,3,2,4,5] sorted? " + isSorted(unsorted));outputFirst 10: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Last 10: [991, 992, 993, 994, 995, 996, 997, 998, 999, 1000] Verify sorted:static boolean isSorted(int[] arr)
pass 1 of 266static boolean isSorted(int[] arr) {67 for (int i = 0; i < arr.length - 1; i++) {for (int i = 0; i < arr.length - 1; i++)
pass 1 of 666static boolean isSorted(int[] arr) {67 for (int i0 = 0; i < arr.length5 - 1; i++) {68 if (arr[i] > arr[i + 1]) return false;All 6 passes — pass 1 is the card above pass iarr[i]arr[i + 1]1 0 — — 2 1 — — 3 2 — — 4 3 — — 5 0 — — 6 1 3 2 return true;
69 }70 return true;71}System.out.println("Is [1,2,3,4,5] sorted? " + isSorted(sorted));
62 System.out.println("Is [1,2,3,4,5] sorted? " + isSorted(sorted));63 System.out.println("Is [1,3,2,4,5] sorted? " + isSorted(unsorted));64}outputIs [1,2,3,4,5] sorted? truestatic boolean isSorted(int[] arr)
pass 2 of 266static boolean isSorted(int[] arr) {67 for (int i = 0; i < arr.length - 1; i++) {if (arr[i] > arr[i + 1])
67for (int i = 0; i < arr.length - 1; i++) {68 if (arr[i]3 > arr[i + 1]2) return false;69}values this step1iSystem.out.println("Is [1,3,2,4,5] sorted? " + isSorted(unsorted));
62 System.out.println("Is [1,2,3,4,5] sorted? " + isSorted(sorted));63 System.out.println("Is [1,3,2,4,5] sorted? " + isSorted(unsorted));64}outputIs [1,3,2,4,5] sorted? false
In-place sorting
Arrays.sort() modifies the original array rather than creating a new one, saving memory for large arrays.
Searching Arrays
Find elements efficiently using binary search.
Search.java
Replay: real traced execution (multi-file project)
// Arrays.binarySearch examples
import java.util.Arrays;
public class Search {
public static void main(String[] args) {
System.out.println("Binary search basics:");
int[] nums = {1, 3, 5, 7, 9, 11, 13};
System.out.println("Array: " + Arrays.toString(nums));
int index = Arrays.binarySearch(nums, 7);
System.out.println("Search 7: index = " + index);
index = Arrays.binarySearch(nums, 9);
System.out.println("Search 9: index = " + index);
index = Arrays.binarySearch(nums, 1);
System.out.println("Search 1: index = " + index);
System.out.println("\nElement not found:");
index = Arrays.binarySearch(nums, 8);
System.out.println("Search 8: index = " + index);
System.out.println("Insertion point: " + (-index - 1));
index = Arrays.binarySearch(nums, 0);
System.out.println("Search 0: index = " + index);
System.out.println("Insertion point: " + (-index - 1));
index = Arrays.binarySearch(nums, 20);
System.out.println("Search 20: index = " + index);
System.out.println("Insertion point: " + (-index - 1));
System.out.println("\nSearch in range:");
int[] values = {10, 20, 30, 40, 50, 60, 70};
System.out.println("Array: " + Arrays.toString(values));
// Search only in indices 2-5
index = Arrays.binarySearch(values, 2, 5, 40);
System.out.println("Search 40 in [2,5): index = " + index);
index = Arrays.binarySearch(values, 2, 5, 60);
System.out.println("Search 60 in [2,5): index = " + index + " (not in range)");
System.out.println("\nSearch strings:");
String[] fruits = {"apple", "banana", "cherry", "date", "grape"};
System.out.println("Array: " + Arrays.toString(fruits));
index = Arrays.binarySearch(fruits, "cherry");
System.out.println("Search 'cherry': index = " + index);
index = Arrays.binarySearch(fruits, "kiwi");
System.out.println("Search 'kiwi': index = " + index);
System.out.println("\nUnsorted array (WRONG):");
int[] unsorted = {5, 2, 8, 1, 9};
System.out.println("Unsorted: " + Arrays.toString(unsorted));
index = Arrays.binarySearch(unsorted, 8);
System.out.println("Search 8: index = " + index + " (unreliable)");
// Must sort first
Arrays.sort(unsorted);
System.out.println("Sorted: " + Arrays.toString(unsorted));
index = Arrays.binarySearch(unsorted, 8);
System.out.println("Search 8: index = " + index + " (correct)");
System.out.println("\nInsert element:");
int[] arr = {1, 3, 5, 7, 9};
int newValue = 6;
System.out.println("Original: " + Arrays.toString(arr));
index = Arrays.binarySearch(arr, newValue);
if (index < 0) {
int insertPos = -index - 1;
System.out.println("Insert " + newValue + " at position " + insertPos);
int[] newArr = new int[arr.length + 1];
System.arraycopy(arr, 0, newArr, 0, insertPos);
newArr[insertPos] = newValue;
System.arraycopy(arr, insertPos, newArr, insertPos + 1, arr.length - insertPos);
System.out.println("After insert: " + Arrays.toString(newArr));
}
System.out.println("\nCustom comparator search:");
String[] words = {"a", "bb", "ccc", "dddd", "eeeee"};
System.out.println("Array: " + Arrays.toString(words));
// Search by length
String target = "xxx"; // length 3
index = Arrays.binarySearch(words, target,
(a, b) -> a.length() - b.length());
System.out.println("Search length 3: index = " + index);
System.out.println("\nFind closest value:");
int[] data = {10, 25, 40, 55, 70, 85, 100};
int searchValue = 60;
System.out.println("Array: " + Arrays.toString(data));
System.out.println("Search value: " + searchValue);
index = Arrays.binarySearch(data, searchValue);
if (index < 0) {
int insertPos = -index - 1;
int closest;
if (insertPos == 0) {
closest = data[0];
} else if (insertPos == data.length) {
closest = data[data.length - 1];
} else {
int left = data[insertPos - 1];
int right = data[insertPos];
closest = (searchValue - left < right - searchValue) ? left : right;
}
System.out.println("Closest value: " + closest);
} else {
System.out.println("Exact match: " + data[index]);
}
}
}
// Arrays.binarySearch examples
import java.util.Arrays;
public class Search {
public static void main(String[] args) {
System.out.println("Binary search basics:");
int[] nums = {1, 3, 5, 7, 9, 11, 13};
System.out.println("Array: " + Arrays.toString(nums));
int index = Arrays.binarySearch(nums, 7);
System.out.println("Search 7: index = " + index);
index = Arrays.binarySearch(nums, 9);
System.out.println("Search 9: index = " + index);
index = Arrays.binarySearch(nums, 1);
System.out.println("Search 1: index = " + index);
System.out.println("\nElement not found:");
index = Arrays.binarySearch(nums, 8);
System.out.println("Search 8: index = " + index);
System.out.println("Insertion point: " + (-index - 1));
index = Arrays.binarySearch(nums, 0);
System.out.println("Search 0: index = " + index);
System.out.println("Insertion point: " + (-index - 1));
index = Arrays.binarySearch(nums, 20);
System.out.println("Search 20: index = " + index);
System.out.println("Insertion point: " + (-index - 1));
System.out.println("\nSearch in range:");
int[] values = {10, 20, 30, 40, 50, 60, 70};
System.out.println("Array: " + Arrays.toString(values));
// Search only in indices 2-5
index = Arrays.binarySearch(values, 2, 5, 40);
System.out.println("Search 40 in [2,5): index = " + index);
index = Arrays.binarySearch(values, 2, 5, 60);
System.out.println("Search 60 in [2,5): index = " + index + " (not in range)");
System.out.println("\nSearch strings:");
String[] fruits = {"apple", "banana", "cherry", "date", "grape"};
System.out.println("Array: " + Arrays.toString(fruits));
index = Arrays.binarySearch(fruits, "cherry");
System.out.println("Search 'cherry': index = " + index);
index = Arrays.binarySearch(fruits, "kiwi");
System.out.println("Search 'kiwi': index = " + index);
System.out.println("\nUnsorted array (WRONG):");
int[] unsorted = {5, 2, 8, 1, 9};
System.out.println("Unsorted: " + Arrays.toString(unsorted));
index = Arrays.binarySearch(unsorted, 8);
System.out.println("Search 8: index = " + index + " (unreliable)");
// Must sort first
Arrays.sort(unsorted);
System.out.println("Sorted: " + Arrays.toString(unsorted));
index = Arrays.binarySearch(unsorted, 8);
System.out.println("Search 8: index = " + index + " (correct)");
System.out.println("\nInsert element:");
int[] arr = {1, 3, 5, 7, 9};
int newValue = 4;
System.out.println("Original: " + Arrays.toString(arr));
index = Arrays.binarySearch(arr, newValue);
if (index < 0) {
int insertPos = -index - 1;
System.out.println("Insert " + newValue + " at position " + insertPos);
int[] newArr = new int[arr.length + 1];
System.arraycopy(arr, 0, newArr, 0, insertPos);
newArr[insertPos] = newValue;
System.arraycopy(arr, insertPos, newArr, insertPos + 1, arr.length - insertPos);
System.out.println("After insert: " + Arrays.toString(newArr));
}
System.out.println("\nCustom comparator search:");
String[] words = {"a", "bb", "ccc", "dddd", "eeeee"};
System.out.println("Array: " + Arrays.toString(words));
// Search by length
String target = "xxx"; // length 3
index = Arrays.binarySearch(words, target,
(a, b) -> a.length() - b.length());
System.out.println("Search length 3: index = " + index);
System.out.println("\nFind closest value:");
int[] data = {10, 25, 40, 55, 70, 85, 100};
int searchValue = 60;
System.out.println("Array: " + Arrays.toString(data));
System.out.println("Search value: " + searchValue);
index = Arrays.binarySearch(data, searchValue);
if (index < 0) {
int insertPos = -index - 1;
int closest;
if (insertPos == 0) {
closest = data[0];
} else if (insertPos == data.length) {
closest = data[data.length - 1];
} else {
int left = data[insertPos - 1];
int right = data[insertPos];
closest = (searchValue - left < right - searchValue) ? left : right;
}
System.out.println("Closest value: " + closest);
} else {
System.out.println("Exact match: " + data[index]);
}
}
}
// Arrays.binarySearch examples
import java.util.Arrays;
public class Search {
public static void main(String[] args) {
System.out.println("Binary search basics:");
int[] nums = {1, 3, 5, 7, 9, 11, 13};
System.out.println("Array: " + Arrays.toString(nums));
int index = Arrays.binarySearch(nums, 7);
System.out.println("Search 7: index = " + index);
index = Arrays.binarySearch(nums, 9);
System.out.println("Search 9: index = " + index);
index = Arrays.binarySearch(nums, 1);
System.out.println("Search 1: index = " + index);
System.out.println("\nElement not found:");
index = Arrays.binarySearch(nums, 8);
System.out.println("Search 8: index = " + index);
System.out.println("Insertion point: " + (-index - 1));
index = Arrays.binarySearch(nums, 0);
System.out.println("Search 0: index = " + index);
System.out.println("Insertion point: " + (-index - 1));
index = Arrays.binarySearch(nums, 20);
System.out.println("Search 20: index = " + index);
System.out.println("Insertion point: " + (-index - 1));
System.out.println("\nSearch in range:");
int[] values = {10, 20, 30, 40, 50, 60, 70};
System.out.println("Array: " + Arrays.toString(values));
// Search only in indices 2-5
index = Arrays.binarySearch(values, 2, 5, 40);
System.out.println("Search 40 in [2,5): index = " + index);
index = Arrays.binarySearch(values, 2, 5, 60);
System.out.println("Search 60 in [2,5): index = " + index + " (not in range)");
System.out.println("\nSearch strings:");
String[] fruits = {"apple", "banana", "cherry", "date", "grape"};
System.out.println("Array: " + Arrays.toString(fruits));
index = Arrays.binarySearch(fruits, "cherry");
System.out.println("Search 'cherry': index = " + index);
index = Arrays.binarySearch(fruits, "kiwi");
System.out.println("Search 'kiwi': index = " + index);
System.out.println("\nUnsorted array (WRONG):");
int[] unsorted = {5, 2, 8, 1, 9};
System.out.println("Unsorted: " + Arrays.toString(unsorted));
index = Arrays.binarySearch(unsorted, 8);
System.out.println("Search 8: index = " + index + " (unreliable)");
// Must sort first
Arrays.sort(unsorted);
System.out.println("Sorted: " + Arrays.toString(unsorted));
index = Arrays.binarySearch(unsorted, 8);
System.out.println("Search 8: index = " + index + " (correct)");
System.out.println("\nInsert element:");
int[] arr = {1, 3, 5, 7, 9};
int newValue = 10;
System.out.println("Original: " + Arrays.toString(arr));
index = Arrays.binarySearch(arr, newValue);
if (index < 0) {
int insertPos = -index - 1;
System.out.println("Insert " + newValue + " at position " + insertPos);
int[] newArr = new int[arr.length + 1];
System.arraycopy(arr, 0, newArr, 0, insertPos);
newArr[insertPos] = newValue;
System.arraycopy(arr, insertPos, newArr, insertPos + 1, arr.length - insertPos);
System.out.println("After insert: " + Arrays.toString(newArr));
}
System.out.println("\nCustom comparator search:");
String[] words = {"a", "bb", "ccc", "dddd", "eeeee"};
System.out.println("Array: " + Arrays.toString(words));
// Search by length
String target = "xxx"; // length 3
index = Arrays.binarySearch(words, target,
(a, b) -> a.length() - b.length());
System.out.println("Search length 3: index = " + index);
System.out.println("\nFind closest value:");
int[] data = {10, 25, 40, 55, 70, 85, 100};
int searchValue = 60;
System.out.println("Array: " + Arrays.toString(data));
System.out.println("Search value: " + searchValue);
index = Arrays.binarySearch(data, searchValue);
if (index < 0) {
int insertPos = -index - 1;
int closest;
if (insertPos == 0) {
closest = data[0];
} else if (insertPos == data.length) {
closest = data[data.length - 1];
} else {
int left = data[insertPos - 1];
int right = data[insertPos];
closest = (searchValue - left < right - searchValue) ? left : right;
}
System.out.println("Closest value: " + closest);
} else {
System.out.println("Exact match: " + data[index]);
}
}
}
// Arrays.binarySearch examples
import java.util.Arrays;
public class Search {
public static void main(String[] args) {
System.out.println("Binary search basics:");
int[] nums = {1, 3, 5, 7, 9, 11, 13};
System.out.println("Array: " + Arrays.toString(nums));
int index = Arrays.binarySearch(nums, 7);
System.out.println("Search 7: index = " + index);
index = Arrays.binarySearch(nums, 9);
System.out.println("Search 9: index = " + index);
index = Arrays.binarySearch(nums, 1);
System.out.println("Search 1: index = " + index);
System.out.println("\nElement not found:");
index = Arrays.binarySearch(nums, 8);
System.out.println("Search 8: index = " + index);
System.out.println("Insertion point: " + (-index - 1));
index = Arrays.binarySearch(nums, 0);
System.out.println("Search 0: index = " + index);
System.out.println("Insertion point: " + (-index - 1));
index = Arrays.binarySearch(nums, 20);
System.out.println("Search 20: index = " + index);
System.out.println("Insertion point: " + (-index - 1));
System.out.println("\nSearch in range:");
int[] values = {10, 20, 30, 40, 50, 60, 70};
System.out.println("Array: " + Arrays.toString(values));
// Search only in indices 2-5
index = Arrays.binarySearch(values, 2, 5, 40);
System.out.println("Search 40 in [2,5): index = " + index);
index = Arrays.binarySearch(values, 2, 5, 60);
System.out.println("Search 60 in [2,5): index = " + index + " (not in range)");
System.out.println("\nSearch strings:");
String[] fruits = {"apple", "banana", "cherry", "date", "grape"};
System.out.println("Array: " + Arrays.toString(fruits));
index = Arrays.binarySearch(fruits, "cherry");
System.out.println("Search 'cherry': index = " + index);
index = Arrays.binarySearch(fruits, "kiwi");
System.out.println("Search 'kiwi': index = " + index);
System.out.println("\nUnsorted array (WRONG):");
int[] unsorted = {5, 2, 8, 1, 9};
System.out.println("Unsorted: " + Arrays.toString(unsorted));
index = Arrays.binarySearch(unsorted, 8);
System.out.println("Search 8: index = " + index + " (unreliable)");
// Must sort first
Arrays.sort(unsorted);
System.out.println("Sorted: " + Arrays.toString(unsorted));
index = Arrays.binarySearch(unsorted, 8);
System.out.println("Search 8: index = " + index + " (correct)");
System.out.println("\nInsert element:");
int[] arr = {1, 3, 5, 7, 9};
int newValue = 6;
System.out.println("Original: " + Arrays.toString(arr));
index = Arrays.binarySearch(arr, newValue);
if (index < 0) {
int insertPos = -index - 1;
System.out.println("Insert " + newValue + " at position " + insertPos);
int[] newArr = new int[arr.length + 1];
System.arraycopy(arr, 0, newArr, 0, insertPos);
newArr[insertPos] = newValue;
System.arraycopy(arr, insertPos, newArr, insertPos + 1, arr.length - insertPos);
System.out.println("After insert: " + Arrays.toString(newArr));
}
System.out.println("\nCustom comparator search:");
String[] words = {"a", "bb", "ccc", "dddd", "eeeee"};
System.out.println("Array: " + Arrays.toString(words));
// Search by length
String target = "xxx"; // length 3
index = Arrays.binarySearch(words, target,
(a, b) -> a.length() - b.length());
System.out.println("Search length 3: index = " + index);
System.out.println("\nFind closest value:");
int[] data = {10, 25, 40, 55, 70, 85, 100};
int searchValue = 25;
System.out.println("Array: " + Arrays.toString(data));
System.out.println("Search value: " + searchValue);
index = Arrays.binarySearch(data, searchValue);
if (index < 0) {
int insertPos = -index - 1;
int closest;
if (insertPos == 0) {
closest = data[0];
} else if (insertPos == data.length) {
closest = data[data.length - 1];
} else {
int left = data[insertPos - 1];
int right = data[insertPos];
closest = (searchValue - left < right - searchValue) ? left : right;
}
System.out.println("Closest value: " + closest);
} else {
System.out.println("Exact match: " + data[index]);
}
}
}
// Arrays.binarySearch examples
import java.util.Arrays;
public class Search {
public static void main(String[] args) {
System.out.println("Binary search basics:");
int[] nums = {1, 3, 5, 7, 9, 11, 13};
System.out.println("Array: " + Arrays.toString(nums));
int index = Arrays.binarySearch(nums, 7);
System.out.println("Search 7: index = " + index);
index = Arrays.binarySearch(nums, 9);
System.out.println("Search 9: index = " + index);
index = Arrays.binarySearch(nums, 1);
System.out.println("Search 1: index = " + index);
System.out.println("\nElement not found:");
index = Arrays.binarySearch(nums, 8);
System.out.println("Search 8: index = " + index);
System.out.println("Insertion point: " + (-index - 1));
index = Arrays.binarySearch(nums, 0);
System.out.println("Search 0: index = " + index);
System.out.println("Insertion point: " + (-index - 1));
index = Arrays.binarySearch(nums, 20);
System.out.println("Search 20: index = " + index);
System.out.println("Insertion point: " + (-index - 1));
System.out.println("\nSearch in range:");
int[] values = {10, 20, 30, 40, 50, 60, 70};
System.out.println("Array: " + Arrays.toString(values));
// Search only in indices 2-5
index = Arrays.binarySearch(values, 2, 5, 40);
System.out.println("Search 40 in [2,5): index = " + index);
index = Arrays.binarySearch(values, 2, 5, 60);
System.out.println("Search 60 in [2,5): index = " + index + " (not in range)");
System.out.println("\nSearch strings:");
String[] fruits = {"apple", "banana", "cherry", "date", "grape"};
System.out.println("Array: " + Arrays.toString(fruits));
index = Arrays.binarySearch(fruits, "cherry");
System.out.println("Search 'cherry': index = " + index);
index = Arrays.binarySearch(fruits, "kiwi");
System.out.println("Search 'kiwi': index = " + index);
System.out.println("\nUnsorted array (WRONG):");
int[] unsorted = {5, 2, 8, 1, 9};
System.out.println("Unsorted: " + Arrays.toString(unsorted));
index = Arrays.binarySearch(unsorted, 8);
System.out.println("Search 8: index = " + index + " (unreliable)");
// Must sort first
Arrays.sort(unsorted);
System.out.println("Sorted: " + Arrays.toString(unsorted));
index = Arrays.binarySearch(unsorted, 8);
System.out.println("Search 8: index = " + index + " (correct)");
System.out.println("\nInsert element:");
int[] arr = {1, 3, 5, 7, 9};
int newValue = 6;
System.out.println("Original: " + Arrays.toString(arr));
index = Arrays.binarySearch(arr, newValue);
if (index < 0) {
int insertPos = -index - 1;
System.out.println("Insert " + newValue + " at position " + insertPos);
int[] newArr = new int[arr.length + 1];
System.arraycopy(arr, 0, newArr, 0, insertPos);
newArr[insertPos] = newValue;
System.arraycopy(arr, insertPos, newArr, insertPos + 1, arr.length - insertPos);
System.out.println("After insert: " + Arrays.toString(newArr));
}
System.out.println("\nCustom comparator search:");
String[] words = {"a", "bb", "ccc", "dddd", "eeeee"};
System.out.println("Array: " + Arrays.toString(words));
// Search by length
String target = "xxx"; // length 3
index = Arrays.binarySearch(words, target,
(a, b) -> a.length() - b.length());
System.out.println("Search length 3: index = " + index);
System.out.println("\nFind closest value:");
int[] data = {10, 25, 40, 55, 70, 85, 100};
int searchValue = 90;
System.out.println("Array: " + Arrays.toString(data));
System.out.println("Search value: " + searchValue);
index = Arrays.binarySearch(data, searchValue);
if (index < 0) {
int insertPos = -index - 1;
int closest;
if (insertPos == 0) {
closest = data[0];
} else if (insertPos == data.length) {
closest = data[data.length - 1];
} else {
int left = data[insertPos - 1];
int right = data[insertPos];
closest = (searchValue - left < right - searchValue) ? left : right;
}
System.out.println("Closest value: " + closest);
} else {
System.out.println("Exact match: " + data[index]);
}
}
}
index ← 3, newValue ← 6
5public class Search {6 public static void main(String[] args) {7 System.out.println("Binary search basics:");8 int[] nums = {1, 3, 5, 7, 9, 11, 13};9 System.out.println("Array: " + Arrays.toString(nums));1011 int index→ 3 = Arrays.binarySearch(nums, 7);12 System.out.println("Search 7: index = " + index3);1314 index→ 4 = Arrays.binarySearch(nums, 9);15 System.out.println("Search 9: index = " + index4);1617 index→ 0 = Arrays.binarySearch(nums, 1);18 System.out.println("Search 1: index = " + index0);19 System.out.println("\nElement not found:");20 index→ -5 = Arrays.binarySearch(nums, 8);21 System.out.println("Search 8: index = " + index-5);22 System.out.println("Insertion point: " + (-index-5 - 1));2324 index→ -1 = Arrays.binarySearch(nums, 0);25 System.out.println("Search 0: index = " + index-1);26 System.out.println("Insertion point: " + (-index-1 - 1));2728 index→ -8 = Arrays.binarySearch(nums, 20);29 System.out.println("Search 20: index = " + index-8);30 System.out.println("Insertion point: " + (-index-8 - 1));31 System.out.println("\nSearch in range:");32 int[] values = {10, 20, 30, 40, 50, 60, 70};33 System.out.println("Array: " + Arrays.toString(values));3435 // Search only in indices 2-536 index→ 3 = Arrays.binarySearch(values, 2, 5, 40);37 System.out.println("Search 40 in [2,5): index = " + index3);3839 index→ -6 = Arrays.binarySearch(values, 2, 5, 60);40 System.out.println("Search 60 in [2,5): index = " + index-6 + " (not in range)");41 System.out.println("\nSearch strings:");42 String[] fruits = {"apple", "banana", "cherry", "date", "grape"};43 System.out.println("Array: " + Arrays.toString(fruits));4445 index→ 2 = Arrays.binarySearch(fruits, "cherry");46 System.out.println("Search 'cherry': index = " + index2);4748 index→ -6 = Arrays.binarySearch(fruits, "kiwi");49 System.out.println("Search 'kiwi': index = " + index-6);50 System.out.println("\nUnsorted array (WRONG):");51 int[] unsorted = {5, 2, 8, 1, 9};52 System.out.println("Unsorted: " + Arrays.toString(unsorted));5354 index→ 2 = Arrays.binarySearch(unsorted, 8);55 System.out.println("Search 8: index = " + index2 + " (unreliable)");5657 // Must sort first58 Arrays.sort(unsorted);59 System.out.println("Sorted: " + Arrays.toString(unsorted));60 index→ 3 = Arrays.binarySearch(unsorted, 8);61 System.out.println("Search 8: index = " + index3 + " (correct)");62 System.out.println("\nInsert element:");63 int[] arr = {1, 3, 5, 7, 9};64 int newValue→ 6 = 6; //@newValue=4, 106566 System.out.println("Original: " + Arrays.toString(arr));67 index→ -4 = Arrays.binarySearch(arr, newValue6);outputBinary search basics: Array: [1, 3, 5, 7, 9, 11, 13] Search 7: index = 3 Search 9: index = 4 Search 1: index = 0 Element not found: Search 8: index = -5 Insertion point: 4 Search 0: index = -1 Insertion point: 0 Search 20: index = -8 Insertion point: 7 Search in range: Array: [10, 20, 30, 40, 50, 60, 70] Search 40 in [2,5): index = 3 Search 60 in [2,5): index = -6 (not in range) Search strings: Array: [apple, banana, cherry, date, grape] Search 'cherry': index = 2 Search 'kiwi': index = -6 Unsorted array (WRONG): Unsorted: [5, 2, 8, 1, 9] Search 8: index = 2 (unreliable) Sorted: [1, 2, 5, 8, 9] Search 8: index = 3 (correct) Insert element: Original: [1, 3, 5, 7, 9]insertPos ← 3, newArr[insertPos] ← 6
69if (index-4 < 0) {70 int insertPos→ 3 = -index-4 - 1;71 System.out.println("Insert " + newValue6 + " at position " + insertPos3);7273 int[] newArr = new int[arr.length5 + 1];74 System.arraycopy(arr, 0, newArr, 0, insertPos3);75 newArr[insertPos]→ 6 = newValue6;76 System.arraycopy(arr, insertPos3, newArr, insertPos + 1, arr.length5 - insertPos);7778 System.out.println("After insert: " + Arrays.toString(newArr));79}outputInsert 6 at position 3 After insert: [1, 3, 5, 6, 7, 9]target ← xxx, index ← 2, searchValue ← 60
79}80System.out.println("\nCustom comparator search:");81String[] words = {"a", "bb", "ccc", "dddd", "eeeee"};82System.out.println("Array: " + Arrays.toString(words));8384// Search by length85String target→ xxx = "xxx"; // length 386index→ 2 = Arrays.binarySearch(words, targetxxx,87 (a, b) -> a.length() - b.length());88System.out.println("Search length 3: index = " + index2);89System.out.println("\nFind closest value:");90int[] data = {10, 25, 40, 55, 70, 85, 100};91int searchValue→ 60 = 60; //@searchValue=25, 909293System.out.println("Array: " + Arrays.toString(data));94System.out.println("Search value: " + searchValue60);9596index→ -5 = Arrays.binarySearch(data, searchValue60);97if (index < 0) {output Custom comparator search: Array: [a, bb, ccc, dddd, eeeee] Search length 3: index = 2 Find closest value: Array: [10, 25, 40, 55, 70, 85, 100] Search value: 60insertPos ← 4
96index = Arrays.binarySearch(data, searchValue);97if (index-5 < 0) {98 int insertPos→ 4 = -index-5 - 1;99100 int closest;101 if (insertPos == 0) {left ← 55, right ← 70, closest ← 55
104 closest = data[data.length - 1];105} else {106 int left→ 55 = data[insertPos - 1]55;107 int right→ 70 = data[insertPos]70;108 closest→ 55 = (searchValue60 - left55 < right70 - searchValue) ? left : right;109}values this step4insertPosSystem.out.println("Closest value: " + closest);
111 System.out.println("Closest value: " + closest55);112} else {outputClosest value: 55
index ← 3, newValue ← 4
5public class Search {6 public static void main(String[] args) {7 System.out.println("Binary search basics:");8 int[] nums = {1, 3, 5, 7, 9, 11, 13};9 System.out.println("Array: " + Arrays.toString(nums));1011 int index→ 3 = Arrays.binarySearch(nums, 7);12 System.out.println("Search 7: index = " + index3);1314 index→ 4 = Arrays.binarySearch(nums, 9);15 System.out.println("Search 9: index = " + index4);1617 index→ 0 = Arrays.binarySearch(nums, 1);18 System.out.println("Search 1: index = " + index0);19 System.out.println("\nElement not found:");20 index→ -5 = Arrays.binarySearch(nums, 8);21 System.out.println("Search 8: index = " + index-5);22 System.out.println("Insertion point: " + (-index-5 - 1));2324 index→ -1 = Arrays.binarySearch(nums, 0);25 System.out.println("Search 0: index = " + index-1);26 System.out.println("Insertion point: " + (-index-1 - 1));2728 index→ -8 = Arrays.binarySearch(nums, 20);29 System.out.println("Search 20: index = " + index-8);30 System.out.println("Insertion point: " + (-index-8 - 1));31 System.out.println("\nSearch in range:");32 int[] values = {10, 20, 30, 40, 50, 60, 70};33 System.out.println("Array: " + Arrays.toString(values));3435 // Search only in indices 2-536 index→ 3 = Arrays.binarySearch(values, 2, 5, 40);37 System.out.println("Search 40 in [2,5): index = " + index3);3839 index→ -6 = Arrays.binarySearch(values, 2, 5, 60);40 System.out.println("Search 60 in [2,5): index = " + index-6 + " (not in range)");41 System.out.println("\nSearch strings:");42 String[] fruits = {"apple", "banana", "cherry", "date", "grape"};43 System.out.println("Array: " + Arrays.toString(fruits));4445 index→ 2 = Arrays.binarySearch(fruits, "cherry");46 System.out.println("Search 'cherry': index = " + index2);4748 index→ -6 = Arrays.binarySearch(fruits, "kiwi");49 System.out.println("Search 'kiwi': index = " + index-6);50 System.out.println("\nUnsorted array (WRONG):");51 int[] unsorted = {5, 2, 8, 1, 9};52 System.out.println("Unsorted: " + Arrays.toString(unsorted));5354 index→ 2 = Arrays.binarySearch(unsorted, 8);55 System.out.println("Search 8: index = " + index2 + " (unreliable)");5657 // Must sort first58 Arrays.sort(unsorted);59 System.out.println("Sorted: " + Arrays.toString(unsorted));60 index→ 3 = Arrays.binarySearch(unsorted, 8);61 System.out.println("Search 8: index = " + index3 + " (correct)");62 System.out.println("\nInsert element:");63 int[] arr = {1, 3, 5, 7, 9};64 int newValue→ 4 = 4;6566 System.out.println("Original: " + Arrays.toString(arr));67 index→ -3 = Arrays.binarySearch(arr, newValue4);outputBinary search basics: Array: [1, 3, 5, 7, 9, 11, 13] Search 7: index = 3 Search 9: index = 4 Search 1: index = 0 Element not found: Search 8: index = -5 Insertion point: 4 Search 0: index = -1 Insertion point: 0 Search 20: index = -8 Insertion point: 7 Search in range: Array: [10, 20, 30, 40, 50, 60, 70] Search 40 in [2,5): index = 3 Search 60 in [2,5): index = -6 (not in range) Search strings: Array: [apple, banana, cherry, date, grape] Search 'cherry': index = 2 Search 'kiwi': index = -6 Unsorted array (WRONG): Unsorted: [5, 2, 8, 1, 9] Search 8: index = 2 (unreliable) Sorted: [1, 2, 5, 8, 9] Search 8: index = 3 (correct) Insert element: Original: [1, 3, 5, 7, 9]insertPos ← 2, newArr[insertPos] ← 4
69if (index-3 < 0) {70 int insertPos→ 2 = -index-3 - 1;71 System.out.println("Insert " + newValue4 + " at position " + insertPos2);7273 int[] newArr = new int[arr.length5 + 1];74 System.arraycopy(arr, 0, newArr, 0, insertPos2);75 newArr[insertPos]→ 4 = newValue4;76 System.arraycopy(arr, insertPos2, newArr, insertPos + 1, arr.length5 - insertPos);7778 System.out.println("After insert: " + Arrays.toString(newArr));79}outputInsert 4 at position 2 After insert: [1, 3, 4, 5, 7, 9]target ← xxx, index ← 2, searchValue ← 60
79}80System.out.println("\nCustom comparator search:");81String[] words = {"a", "bb", "ccc", "dddd", "eeeee"};82System.out.println("Array: " + Arrays.toString(words));8384// Search by length85String target→ xxx = "xxx"; // length 386index→ 2 = Arrays.binarySearch(words, targetxxx,87 (a, b) -> a.length() - b.length());88System.out.println("Search length 3: index = " + index2);89System.out.println("\nFind closest value:");90int[] data = {10, 25, 40, 55, 70, 85, 100};91int searchValue→ 60 = 60;9293System.out.println("Array: " + Arrays.toString(data));94System.out.println("Search value: " + searchValue60);9596index→ -5 = Arrays.binarySearch(data, searchValue60);97if (index < 0) {output Custom comparator search: Array: [a, bb, ccc, dddd, eeeee] Search length 3: index = 2 Find closest value: Array: [10, 25, 40, 55, 70, 85, 100] Search value: 60insertPos ← 4
96index = Arrays.binarySearch(data, searchValue);97if (index-5 < 0) {98 int insertPos→ 4 = -index-5 - 1;99100 int closest;101 if (insertPos == 0) {left ← 55, right ← 70, closest ← 55
104 closest = data[data.length - 1];105} else {106 int left→ 55 = data[insertPos - 1]55;107 int right→ 70 = data[insertPos]70;108 closest→ 55 = (searchValue60 - left55 < right70 - searchValue) ? left : right;109}values this step4insertPosSystem.out.println("Closest value: " + closest);
111 System.out.println("Closest value: " + closest55);112} else {outputClosest value: 55
index ← 3, newValue ← 10
5public class Search {6 public static void main(String[] args) {7 System.out.println("Binary search basics:");8 int[] nums = {1, 3, 5, 7, 9, 11, 13};9 System.out.println("Array: " + Arrays.toString(nums));1011 int index→ 3 = Arrays.binarySearch(nums, 7);12 System.out.println("Search 7: index = " + index3);1314 index→ 4 = Arrays.binarySearch(nums, 9);15 System.out.println("Search 9: index = " + index4);1617 index→ 0 = Arrays.binarySearch(nums, 1);18 System.out.println("Search 1: index = " + index0);19 System.out.println("\nElement not found:");20 index→ -5 = Arrays.binarySearch(nums, 8);21 System.out.println("Search 8: index = " + index-5);22 System.out.println("Insertion point: " + (-index-5 - 1));2324 index→ -1 = Arrays.binarySearch(nums, 0);25 System.out.println("Search 0: index = " + index-1);26 System.out.println("Insertion point: " + (-index-1 - 1));2728 index→ -8 = Arrays.binarySearch(nums, 20);29 System.out.println("Search 20: index = " + index-8);30 System.out.println("Insertion point: " + (-index-8 - 1));31 System.out.println("\nSearch in range:");32 int[] values = {10, 20, 30, 40, 50, 60, 70};33 System.out.println("Array: " + Arrays.toString(values));3435 // Search only in indices 2-536 index→ 3 = Arrays.binarySearch(values, 2, 5, 40);37 System.out.println("Search 40 in [2,5): index = " + index3);3839 index→ -6 = Arrays.binarySearch(values, 2, 5, 60);40 System.out.println("Search 60 in [2,5): index = " + index-6 + " (not in range)");41 System.out.println("\nSearch strings:");42 String[] fruits = {"apple", "banana", "cherry", "date", "grape"};43 System.out.println("Array: " + Arrays.toString(fruits));4445 index→ 2 = Arrays.binarySearch(fruits, "cherry");46 System.out.println("Search 'cherry': index = " + index2);4748 index→ -6 = Arrays.binarySearch(fruits, "kiwi");49 System.out.println("Search 'kiwi': index = " + index-6);50 System.out.println("\nUnsorted array (WRONG):");51 int[] unsorted = {5, 2, 8, 1, 9};52 System.out.println("Unsorted: " + Arrays.toString(unsorted));5354 index→ 2 = Arrays.binarySearch(unsorted, 8);55 System.out.println("Search 8: index = " + index2 + " (unreliable)");5657 // Must sort first58 Arrays.sort(unsorted);59 System.out.println("Sorted: " + Arrays.toString(unsorted));60 index→ 3 = Arrays.binarySearch(unsorted, 8);61 System.out.println("Search 8: index = " + index3 + " (correct)");62 System.out.println("\nInsert element:");63 int[] arr = {1, 3, 5, 7, 9};64 int newValue→ 10 = 10;6566 System.out.println("Original: " + Arrays.toString(arr));67 index→ -6 = Arrays.binarySearch(arr, newValue10);outputBinary search basics: Array: [1, 3, 5, 7, 9, 11, 13] Search 7: index = 3 Search 9: index = 4 Search 1: index = 0 Element not found: Search 8: index = -5 Insertion point: 4 Search 0: index = -1 Insertion point: 0 Search 20: index = -8 Insertion point: 7 Search in range: Array: [10, 20, 30, 40, 50, 60, 70] Search 40 in [2,5): index = 3 Search 60 in [2,5): index = -6 (not in range) Search strings: Array: [apple, banana, cherry, date, grape] Search 'cherry': index = 2 Search 'kiwi': index = -6 Unsorted array (WRONG): Unsorted: [5, 2, 8, 1, 9] Search 8: index = 2 (unreliable) Sorted: [1, 2, 5, 8, 9] Search 8: index = 3 (correct) Insert element: Original: [1, 3, 5, 7, 9]insertPos ← 5, newArr[insertPos] ← 10
69if (index-6 < 0) {70 int insertPos→ 5 = -index-6 - 1;71 System.out.println("Insert " + newValue10 + " at position " + insertPos5);7273 int[] newArr = new int[arr.length5 + 1];74 System.arraycopy(arr, 0, newArr, 0, insertPos5);75 newArr[insertPos]→ 10 = newValue10;76 System.arraycopy(arr, insertPos5, newArr, insertPos + 1, arr.length5 - insertPos);7778 System.out.println("After insert: " + Arrays.toString(newArr));79}outputInsert 10 at position 5 After insert: [1, 3, 5, 7, 9, 10]target ← xxx, index ← 2, searchValue ← 60
79}80System.out.println("\nCustom comparator search:");81String[] words = {"a", "bb", "ccc", "dddd", "eeeee"};82System.out.println("Array: " + Arrays.toString(words));8384// Search by length85String target→ xxx = "xxx"; // length 386index→ 2 = Arrays.binarySearch(words, targetxxx,87 (a, b) -> a.length() - b.length());88System.out.println("Search length 3: index = " + index2);89System.out.println("\nFind closest value:");90int[] data = {10, 25, 40, 55, 70, 85, 100};91int searchValue→ 60 = 60;9293System.out.println("Array: " + Arrays.toString(data));94System.out.println("Search value: " + searchValue60);9596index→ -5 = Arrays.binarySearch(data, searchValue60);97if (index < 0) {output Custom comparator search: Array: [a, bb, ccc, dddd, eeeee] Search length 3: index = 2 Find closest value: Array: [10, 25, 40, 55, 70, 85, 100] Search value: 60insertPos ← 4
96index = Arrays.binarySearch(data, searchValue);97if (index-5 < 0) {98 int insertPos→ 4 = -index-5 - 1;99100 int closest;101 if (insertPos == 0) {left ← 55, right ← 70, closest ← 55
104 closest = data[data.length - 1];105} else {106 int left→ 55 = data[insertPos - 1]55;107 int right→ 70 = data[insertPos]70;108 closest→ 55 = (searchValue60 - left55 < right70 - searchValue) ? left : right;109}values this step4insertPosSystem.out.println("Closest value: " + closest);
111 System.out.println("Closest value: " + closest55);112} else {outputClosest value: 55
index ← 3, newValue ← 6
5public class Search {6 public static void main(String[] args) {7 System.out.println("Binary search basics:");8 int[] nums = {1, 3, 5, 7, 9, 11, 13};9 System.out.println("Array: " + Arrays.toString(nums));1011 int index→ 3 = Arrays.binarySearch(nums, 7);12 System.out.println("Search 7: index = " + index3);1314 index→ 4 = Arrays.binarySearch(nums, 9);15 System.out.println("Search 9: index = " + index4);1617 index→ 0 = Arrays.binarySearch(nums, 1);18 System.out.println("Search 1: index = " + index0);19 System.out.println("\nElement not found:");20 index→ -5 = Arrays.binarySearch(nums, 8);21 System.out.println("Search 8: index = " + index-5);22 System.out.println("Insertion point: " + (-index-5 - 1));2324 index→ -1 = Arrays.binarySearch(nums, 0);25 System.out.println("Search 0: index = " + index-1);26 System.out.println("Insertion point: " + (-index-1 - 1));2728 index→ -8 = Arrays.binarySearch(nums, 20);29 System.out.println("Search 20: index = " + index-8);30 System.out.println("Insertion point: " + (-index-8 - 1));31 System.out.println("\nSearch in range:");32 int[] values = {10, 20, 30, 40, 50, 60, 70};33 System.out.println("Array: " + Arrays.toString(values));3435 // Search only in indices 2-536 index→ 3 = Arrays.binarySearch(values, 2, 5, 40);37 System.out.println("Search 40 in [2,5): index = " + index3);3839 index→ -6 = Arrays.binarySearch(values, 2, 5, 60);40 System.out.println("Search 60 in [2,5): index = " + index-6 + " (not in range)");41 System.out.println("\nSearch strings:");42 String[] fruits = {"apple", "banana", "cherry", "date", "grape"};43 System.out.println("Array: " + Arrays.toString(fruits));4445 index→ 2 = Arrays.binarySearch(fruits, "cherry");46 System.out.println("Search 'cherry': index = " + index2);4748 index→ -6 = Arrays.binarySearch(fruits, "kiwi");49 System.out.println("Search 'kiwi': index = " + index-6);50 System.out.println("\nUnsorted array (WRONG):");51 int[] unsorted = {5, 2, 8, 1, 9};52 System.out.println("Unsorted: " + Arrays.toString(unsorted));5354 index→ 2 = Arrays.binarySearch(unsorted, 8);55 System.out.println("Search 8: index = " + index2 + " (unreliable)");5657 // Must sort first58 Arrays.sort(unsorted);59 System.out.println("Sorted: " + Arrays.toString(unsorted));60 index→ 3 = Arrays.binarySearch(unsorted, 8);61 System.out.println("Search 8: index = " + index3 + " (correct)");62 System.out.println("\nInsert element:");63 int[] arr = {1, 3, 5, 7, 9};64 int newValue→ 6 = 6;6566 System.out.println("Original: " + Arrays.toString(arr));67 index→ -4 = Arrays.binarySearch(arr, newValue6);outputBinary search basics: Array: [1, 3, 5, 7, 9, 11, 13] Search 7: index = 3 Search 9: index = 4 Search 1: index = 0 Element not found: Search 8: index = -5 Insertion point: 4 Search 0: index = -1 Insertion point: 0 Search 20: index = -8 Insertion point: 7 Search in range: Array: [10, 20, 30, 40, 50, 60, 70] Search 40 in [2,5): index = 3 Search 60 in [2,5): index = -6 (not in range) Search strings: Array: [apple, banana, cherry, date, grape] Search 'cherry': index = 2 Search 'kiwi': index = -6 Unsorted array (WRONG): Unsorted: [5, 2, 8, 1, 9] Search 8: index = 2 (unreliable) Sorted: [1, 2, 5, 8, 9] Search 8: index = 3 (correct) Insert element: Original: [1, 3, 5, 7, 9]insertPos ← 3, newArr[insertPos] ← 6
69if (index-4 < 0) {70 int insertPos→ 3 = -index-4 - 1;71 System.out.println("Insert " + newValue6 + " at position " + insertPos3);7273 int[] newArr = new int[arr.length5 + 1];74 System.arraycopy(arr, 0, newArr, 0, insertPos3);75 newArr[insertPos]→ 6 = newValue6;76 System.arraycopy(arr, insertPos3, newArr, insertPos + 1, arr.length5 - insertPos);7778 System.out.println("After insert: " + Arrays.toString(newArr));79}outputInsert 6 at position 3 After insert: [1, 3, 5, 6, 7, 9]target ← xxx, index ← 2, searchValue ← 25
79}80System.out.println("\nCustom comparator search:");81String[] words = {"a", "bb", "ccc", "dddd", "eeeee"};82System.out.println("Array: " + Arrays.toString(words));8384// Search by length85String target→ xxx = "xxx"; // length 386index→ 2 = Arrays.binarySearch(words, targetxxx,87 (a, b) -> a.length() - b.length());88System.out.println("Search length 3: index = " + index2);89System.out.println("\nFind closest value:");90int[] data = {10, 25, 40, 55, 70, 85, 100};91int searchValue→ 25 = 25;9293System.out.println("Array: " + Arrays.toString(data));94System.out.println("Search value: " + searchValue25);9596index→ 1 = Arrays.binarySearch(data, searchValue25);97if (index < 0) {output Custom comparator search: Array: [a, bb, ccc, dddd, eeeee] Search length 3: index = 2 Find closest value: Array: [10, 25, 40, 55, 70, 85, 100] Search value: 25else
111 System.out.println("Closest value: " + closest);112} else {113 System.out.println("Exact match: " + data[index]25);114}outputExact match: 25values this step1index
index ← 3, newValue ← 6
5public class Search {6 public static void main(String[] args) {7 System.out.println("Binary search basics:");8 int[] nums = {1, 3, 5, 7, 9, 11, 13};9 System.out.println("Array: " + Arrays.toString(nums));1011 int index→ 3 = Arrays.binarySearch(nums, 7);12 System.out.println("Search 7: index = " + index3);1314 index→ 4 = Arrays.binarySearch(nums, 9);15 System.out.println("Search 9: index = " + index4);1617 index→ 0 = Arrays.binarySearch(nums, 1);18 System.out.println("Search 1: index = " + index0);19 System.out.println("\nElement not found:");20 index→ -5 = Arrays.binarySearch(nums, 8);21 System.out.println("Search 8: index = " + index-5);22 System.out.println("Insertion point: " + (-index-5 - 1));2324 index→ -1 = Arrays.binarySearch(nums, 0);25 System.out.println("Search 0: index = " + index-1);26 System.out.println("Insertion point: " + (-index-1 - 1));2728 index→ -8 = Arrays.binarySearch(nums, 20);29 System.out.println("Search 20: index = " + index-8);30 System.out.println("Insertion point: " + (-index-8 - 1));31 System.out.println("\nSearch in range:");32 int[] values = {10, 20, 30, 40, 50, 60, 70};33 System.out.println("Array: " + Arrays.toString(values));3435 // Search only in indices 2-536 index→ 3 = Arrays.binarySearch(values, 2, 5, 40);37 System.out.println("Search 40 in [2,5): index = " + index3);3839 index→ -6 = Arrays.binarySearch(values, 2, 5, 60);40 System.out.println("Search 60 in [2,5): index = " + index-6 + " (not in range)");41 System.out.println("\nSearch strings:");42 String[] fruits = {"apple", "banana", "cherry", "date", "grape"};43 System.out.println("Array: " + Arrays.toString(fruits));4445 index→ 2 = Arrays.binarySearch(fruits, "cherry");46 System.out.println("Search 'cherry': index = " + index2);4748 index→ -6 = Arrays.binarySearch(fruits, "kiwi");49 System.out.println("Search 'kiwi': index = " + index-6);50 System.out.println("\nUnsorted array (WRONG):");51 int[] unsorted = {5, 2, 8, 1, 9};52 System.out.println("Unsorted: " + Arrays.toString(unsorted));5354 index→ 2 = Arrays.binarySearch(unsorted, 8);55 System.out.println("Search 8: index = " + index2 + " (unreliable)");5657 // Must sort first58 Arrays.sort(unsorted);59 System.out.println("Sorted: " + Arrays.toString(unsorted));60 index→ 3 = Arrays.binarySearch(unsorted, 8);61 System.out.println("Search 8: index = " + index3 + " (correct)");62 System.out.println("\nInsert element:");63 int[] arr = {1, 3, 5, 7, 9};64 int newValue→ 6 = 6;6566 System.out.println("Original: " + Arrays.toString(arr));67 index→ -4 = Arrays.binarySearch(arr, newValue6);outputBinary search basics: Array: [1, 3, 5, 7, 9, 11, 13] Search 7: index = 3 Search 9: index = 4 Search 1: index = 0 Element not found: Search 8: index = -5 Insertion point: 4 Search 0: index = -1 Insertion point: 0 Search 20: index = -8 Insertion point: 7 Search in range: Array: [10, 20, 30, 40, 50, 60, 70] Search 40 in [2,5): index = 3 Search 60 in [2,5): index = -6 (not in range) Search strings: Array: [apple, banana, cherry, date, grape] Search 'cherry': index = 2 Search 'kiwi': index = -6 Unsorted array (WRONG): Unsorted: [5, 2, 8, 1, 9] Search 8: index = 2 (unreliable) Sorted: [1, 2, 5, 8, 9] Search 8: index = 3 (correct) Insert element: Original: [1, 3, 5, 7, 9]insertPos ← 3, newArr[insertPos] ← 6
69if (index-4 < 0) {70 int insertPos→ 3 = -index-4 - 1;71 System.out.println("Insert " + newValue6 + " at position " + insertPos3);7273 int[] newArr = new int[arr.length5 + 1];74 System.arraycopy(arr, 0, newArr, 0, insertPos3);75 newArr[insertPos]→ 6 = newValue6;76 System.arraycopy(arr, insertPos3, newArr, insertPos + 1, arr.length5 - insertPos);7778 System.out.println("After insert: " + Arrays.toString(newArr));79}outputInsert 6 at position 3 After insert: [1, 3, 5, 6, 7, 9]target ← xxx, index ← 2, searchValue ← 90
79}80System.out.println("\nCustom comparator search:");81String[] words = {"a", "bb", "ccc", "dddd", "eeeee"};82System.out.println("Array: " + Arrays.toString(words));8384// Search by length85String target→ xxx = "xxx"; // length 386index→ 2 = Arrays.binarySearch(words, targetxxx,87 (a, b) -> a.length() - b.length());88System.out.println("Search length 3: index = " + index2);89System.out.println("\nFind closest value:");90int[] data = {10, 25, 40, 55, 70, 85, 100};91int searchValue→ 90 = 90;9293System.out.println("Array: " + Arrays.toString(data));94System.out.println("Search value: " + searchValue90);9596index→ -7 = Arrays.binarySearch(data, searchValue90);97if (index < 0) {output Custom comparator search: Array: [a, bb, ccc, dddd, eeeee] Search length 3: index = 2 Find closest value: Array: [10, 25, 40, 55, 70, 85, 100] Search value: 90insertPos ← 6
96index = Arrays.binarySearch(data, searchValue);97if (index-7 < 0) {98 int insertPos→ 6 = -index-7 - 1;99100 int closest;101 if (insertPos == 0) {left ← 85, right ← 100, closest ← 85
104 closest = data[data.length - 1];105} else {106 int left→ 85 = data[insertPos - 1]85;107 int right→ 100 = data[insertPos]100;108 closest→ 85 = (searchValue90 - left85 < right100 - searchValue) ? left : right;109}values this step6insertPosSystem.out.println("Closest value: " + closest);
111 System.out.println("Closest value: " + closest85);112} else {outputClosest value: 85
Binary search
Requires a sorted array. Returns the index if found, or a negative value indicating where the element would be inserted.
Copying Arrays
Create copies of arrays or portions of arrays.
Copy.java
Replay: real traced execution (multi-file project)
// Arrays.copyOf and copyOfRange examples
import java.util.Arrays;
public class Copy {
public static void main(String[] args) {
System.out.println("CopyOf basics:");
int[] original = {1, 2, 3, 4, 5};
System.out.println("Original: " + Arrays.toString(original));
int[] copy = Arrays.copyOf(original, original.length);
System.out.println("Copy: " + Arrays.toString(copy));
// Modify copy
copy[0] = 99;
System.out.println("After modifying copy:");
System.out.println("Original: " + Arrays.toString(original));
System.out.println("Copy: " + Arrays.toString(copy));
System.out.println("\nCopy with different length:");
int[] nums = {10, 20, 30, 40, 50};
// Shorter copy
int[] shorter = Arrays.copyOf(nums, 3);
System.out.println("Shorter: " + Arrays.toString(shorter));
// Longer copy (padded with zeros)
int[] longer = Arrays.copyOf(nums, 8);
System.out.println("Longer: " + Arrays.toString(longer));
System.out.println("\nCopyOfRange:");
int[] values = {0, 10, 20, 30, 40, 50, 60, 70};
System.out.println("Original: " + Arrays.toString(values));
// Copy indices 2-5 (exclusive)
int[] range = Arrays.copyOfRange(values, 2, 5);
System.out.println("Range [2,5): " + Arrays.toString(range));
// Copy from middle to end
int[] fromMiddle = Arrays.copyOfRange(values, 3, values.length);
System.out.println("From 3 to end: " + Arrays.toString(fromMiddle));
System.out.println("\nCopy strings:");
String[] fruits = {"apple", "banana", "cherry", "date"};
System.out.println("Original: " + Arrays.toString(fruits));
String[] fruitsCopy = Arrays.copyOf(fruits, fruits.length);
System.out.println("Copy: " + Arrays.toString(fruitsCopy));
fruitsCopy[0] = "apricot";
System.out.println("After change:");
System.out.println("Original: " + Arrays.toString(fruits));
System.out.println("Copy: " + Arrays.toString(fruitsCopy));
System.out.println("\nExtend array:");
int[] arr = {1, 2, 3};
System.out.println("Original: " + Arrays.toString(arr));
// Add element by extending
arr = Arrays.copyOf(arr, arr.length + 1);
arr[arr.length - 1] = 4;
System.out.println("Extended: " + Arrays.toString(arr));
System.out.println("\nTruncate array:");
int[] data = {10, 20, 30, 40, 50, 60};
System.out.println("Original: " + Arrays.toString(data));
data = Arrays.copyOf(data, 4);
System.out.println("Truncated: " + Arrays.toString(data));
System.out.println("\nCopy with padding:");
double[] prices = {9.99, 19.99, 29.99};
System.out.println("Original: " + Arrays.toString(prices));
double[] padded = Arrays.copyOf(prices, 6);
System.out.println("Padded: " + Arrays.toString(padded));
System.out.println("\nExtract subarray:");
int[] scores = {75, 82, 90, 68, 95, 88, 72};
System.out.println("All scores: " + Arrays.toString(scores));
// Get top 3 scores (assuming sorted)
Arrays.sort(scores);
int[] top3 = Arrays.copyOfRange(scores, scores.length - 3, scores.length);
System.out.println("Top 3: " + Arrays.toString(top3));
System.out.println("\nClone 2D array:");
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println("Original matrix:");
for (int[] row : matrix) {
System.out.println(" " + Arrays.toString(row));
}
// Deep copy
int[][] matrixCopy = new int[matrix.length][];
for (int i = 0; i < matrix.length; i++) {
matrixCopy[i] = Arrays.copyOf(matrix[i], matrix[i].length);
}
matrixCopy[0][0] = 99;
System.out.println("After modifying copy:");
System.out.println("Original: " + Arrays.toString(matrix[0]));
System.out.println("Copy: " + Arrays.toString(matrixCopy[0]));
System.out.println("\nSystem.arraycopy:");
int[] src = {10, 20, 30, 40, 50};
int[] dest = new int[3];
System.arraycopy(src, 1, dest, 0, 3); // Copy 3 elements from index 1
System.out.println("Source: " + Arrays.toString(src));
System.out.println("Dest: " + Arrays.toString(dest));
}
}
copy[0] ← 99, fruitsCopy[0] ← apricot, arr.length ← 4, arr[arr.length - 1] ← 4
5public class Copy {6 public static void main(String[] args) {7 System.out.println("CopyOf basics:");8 int[] original = {1, 2, 3, 4, 5};9 System.out.println("Original: " + Arrays.toString(original));1011 int[] copy = Arrays.copyOf(original, original.length5);12 System.out.println("Copy: " + Arrays.toString(copy));1314 // Modify copy15 copy[0]→ 99 = 99;16 System.out.println("After modifying copy:");17 System.out.println("Original: " + Arrays.toString(original));18 System.out.println("Copy: " + Arrays.toString(copy));19 System.out.println("\nCopy with different length:");20 int[] nums = {10, 20, 30, 40, 50};2122 // Shorter copy23 int[] shorter = Arrays.copyOf(nums, 3);24 System.out.println("Shorter: " + Arrays.toString(shorter));2526 // Longer copy (padded with zeros)27 int[] longer = Arrays.copyOf(nums, 8);28 System.out.println("Longer: " + Arrays.toString(longer));29 System.out.println("\nCopyOfRange:");30 int[] values = {0, 10, 20, 30, 40, 50, 60, 70};31 System.out.println("Original: " + Arrays.toString(values));3233 // Copy indices 2-5 (exclusive)34 int[] range = Arrays.copyOfRange(values, 2, 5);35 System.out.println("Range [2,5): " + Arrays.toString(range));3637 // Copy from middle to end38 int[] fromMiddle = Arrays.copyOfRange(values, 3, values.length8);39 System.out.println("From 3 to end: " + Arrays.toString(fromMiddle));40 System.out.println("\nCopy strings:");41 String[] fruits = {"apple", "banana", "cherry", "date"};42 System.out.println("Original: " + Arrays.toString(fruits));4344 String[] fruitsCopy = Arrays.copyOf(fruits, fruits.length4);45 System.out.println("Copy: " + Arrays.toString(fruitsCopy));4647 fruitsCopy[0]→ apricot = "apricot";48 System.out.println("After change:");49 System.out.println("Original: " + Arrays.toString(fruits));50 System.out.println("Copy: " + Arrays.toString(fruitsCopy));51 System.out.println("\nExtend array:");52 int[] arr = {1, 2, 3};53 System.out.println("Original: " + Arrays.toString(arr));5455 // Add element by extending56 arr = Arrays.copyOf(arr, arr.length→ 4 + 1);57 arr[arr.length - 1]→ 4 = 4;58 System.out.println("Extended: " + Arrays.toString(arr));59 System.out.println("\nTruncate array:");60 int[] data = {10, 20, 30, 40, 50, 60};61 System.out.println("Original: " + Arrays.toString(data));6263 data = Arrays.copyOf(data, 4);64 System.out.println("Truncated: " + Arrays.toString(data));65 System.out.println("\nCopy with padding:");66 double[] prices = {9.99, 19.99, 29.99};67 System.out.println("Original: " + Arrays.toString(prices));6869 double[] padded = Arrays.copyOf(prices, 6);70 System.out.println("Padded: " + Arrays.toString(padded));71 System.out.println("\nExtract subarray:");72 int[] scores = {75, 82, 90, 68, 95, 88, 72};73 System.out.println("All scores: " + Arrays.toString(scores));7475 // Get top 3 scores (assuming sorted)76 Arrays.sort(scores);77 int[] top3 = Arrays.copyOfRange(scores, scores.length7 - 3, scores.length);78 System.out.println("Top 3: " + Arrays.toString(top3));79 System.out.println("\nClone 2D array:");80 int[][] matrix = {81 {1, 2, 3},82 {4, 5, 6},83 {7, 8, 9}84 };8586 System.out.println("Original matrix:");87 for (int[] row : matrix) {outputCopyOf basics: Original: [1, 2, 3, 4, 5] Copy: [1, 2, 3, 4, 5] After modifying copy: Original: [1, 2, 3, 4, 5] Copy: [99, 2, 3, 4, 5] Copy with different length: Shorter: [10, 20, 30] Longer: [10, 20, 30, 40, 50, 0, 0, 0] CopyOfRange: Original: [0, 10, 20, 30, 40, 50, 60, 70] Range [2,5): [20, 30, 40] From 3 to end: [30, 40, 50, 60, 70] Copy strings: Original: [apple, banana, cherry, date] Copy: [apple, banana, cherry, date] After change: Original: [apple, banana, cherry, date] Copy: [apricot, banana, cherry, date] Extend array: Original: [1, 2, 3] Extended: [1, 2, 3, 4] Truncate array: Original: [10, 20, 30, 40, 50, 60] Truncated: [10, 20, 30, 40] Copy with padding: Original: [9.99, 19.99, 29.99] Padded: [9.99, 19.99, 29.99, 0.0, 0.0, 0.0] Extract subarray: All scores: [75, 82, 90, 68, 95, 88, 72] Top 3: [88, 90, 95] Clone 2D array: Original matrix:for (int[] row : matrix)
pass 1 of 386System.out.println("Original matrix:");87for (int[] row : matrix) {88 System.out.println(" " + Arrays.toString(row));89}output [1, 2, 3]int[][] matrixCopy = new int[matrix.length][];
91// Deep copy92int[][] matrixCopy = new int[matrix.length][];93for (int i = 0; i < matrix.length; i++) {for (int i = 0; i < matrix.length; i++)
pass 1 of 392int[][] matrixCopy = new int[matrix.length][];93for (int i0 = 0; i < matrix.length3; i++) {94 matrixCopy[i] = Arrays.copyOf(matrix[i], matrix[i].length3);95}All 3 passes — pass 1 is the card above pass i1 0 2 1 3 2 matrixCopy[0][0] ← 99
97 matrixCopy[0][0]→ 99 = 99;9899 System.out.println("After modifying copy:");100 System.out.println("Original: " + Arrays.toString(matrix[0]));101 System.out.println("Copy: " + Arrays.toString(matrixCopy[0]));102 System.out.println("\nSystem.arraycopy:");103 int[] src = {10, 20, 30, 40, 50};104 int[] dest = new int[3];105106 System.arraycopy(src, 1, dest, 0, 3); // Copy 3 elements from index 1107 System.out.println("Source: " + Arrays.toString(src));108 System.out.println("Dest: " + Arrays.toString(dest));109}outputAfter modifying copy: Original: [1, 2, 3] Copy: [99, 2, 3] System.arraycopy: Source: [10, 20, 30, 40, 50] Dest: [20, 30, 40]
Filling Arrays
Initialize arrays with default or specific values.
Fill.java
Replay: real traced execution (multi-file project)
// Arrays.fill examples
import java.util.Arrays;
public class Fill {
public static void main(String[] args) {
System.out.println("Fill entire array:");
int[] nums = new int[10];
Arrays.fill(nums, 42);
System.out.println("Filled with 42: " + Arrays.toString(nums));
System.out.println("\nFill with zero:");
int[] data = {1, 2, 3, 4, 5};
System.out.println("Original: " + Arrays.toString(data));
Arrays.fill(data, 0);
System.out.println("Zeroed: " + Arrays.toString(data));
System.out.println("\nFill range:");
int[] values = new int[10];
Arrays.fill(values, 0, 3, 10); // Fill indices 0-2 with 10
Arrays.fill(values, 3, 7, 20); // Fill indices 3-6 with 20
Arrays.fill(values, 7, 10, 30); // Fill indices 7-9 with 30
System.out.println("Filled: " + Arrays.toString(values));
System.out.println("\nFill strings:");
String[] words = new String[5];
Arrays.fill(words, "hello");
System.out.println("Filled: " + Arrays.toString(words));
System.out.println("\nFill booleans:");
boolean[] flags = new boolean[8];
Arrays.fill(flags, true);
System.out.println("All true: " + Arrays.toString(flags));
Arrays.fill(flags, 2, 6, false);
System.out.println("Middle false: " + Arrays.toString(flags));
System.out.println("\nFill doubles:");
double[] prices = new double[5];
Arrays.fill(prices, 9.99);
System.out.println("Prices: " + Arrays.toString(prices));
System.out.println("\nInitialize grid:");
int[][] grid = new int[3][4];
for (int[] row : grid) {
Arrays.fill(row, -1);
}
System.out.println("Grid initialized to -1:");
for (int[] row : grid) {
System.out.println(" " + Arrays.toString(row));
}
System.out.println("\nFill sections:");
int[] sections = new int[12];
Arrays.fill(sections, 0, 4, 1);
Arrays.fill(sections, 4, 8, 2);
Arrays.fill(sections, 8, 12, 3);
System.out.println("Sections: " + Arrays.toString(sections));
System.out.println("\nReset array:");
int[] scores = {85, 92, 78, 95, 88};
System.out.println("Original scores: " + Arrays.toString(scores));
Arrays.fill(scores, 0);
System.out.println("Reset scores: " + Arrays.toString(scores));
System.out.println("\nMark positions:");
char[] board = new char[9];
Arrays.fill(board, '-');
System.out.println("Empty board: " + Arrays.toString(board));
board[0] = 'X';
board[4] = 'O';
board[8] = 'X';
System.out.println("After moves: " + Arrays.toString(board));
System.out.println("\nFill 2D array row-wise:");
int[][] matrix = new int[4][4];
for (int i = 0; i < matrix.length; i++) {
Arrays.fill(matrix[i], i + 1);
}
System.out.println("Matrix:");
for (int[] row : matrix) {
System.out.println(" " + Arrays.toString(row));
}
}
}
public static void main(String[] args)
5public class Fill {6 public static void main(String[] args) {7 System.out.println("Fill entire array:");8 int[] nums = new int[10];910 Arrays.fill(nums, 42);11 System.out.println("Filled with 42: " + Arrays.toString(nums));12 System.out.println("\nFill with zero:");13 int[] data = {1, 2, 3, 4, 5};14 System.out.println("Original: " + Arrays.toString(data));1516 Arrays.fill(data, 0);17 System.out.println("Zeroed: " + Arrays.toString(data));18 System.out.println("\nFill range:");19 int[] values = new int[10];2021 Arrays.fill(values, 0, 3, 10); // Fill indices 0-2 with 1022 Arrays.fill(values, 3, 7, 20); // Fill indices 3-6 with 2023 Arrays.fill(values, 7, 10, 30); // Fill indices 7-9 with 302425 System.out.println("Filled: " + Arrays.toString(values));26 System.out.println("\nFill strings:");27 String[] words = new String[5];2829 Arrays.fill(words, "hello");30 System.out.println("Filled: " + Arrays.toString(words));31 System.out.println("\nFill booleans:");32 boolean[] flags = new boolean[8];3334 Arrays.fill(flags, true);35 System.out.println("All true: " + Arrays.toString(flags));3637 Arrays.fill(flags, 2, 6, false);38 System.out.println("Middle false: " + Arrays.toString(flags));39 System.out.println("\nFill doubles:");40 double[] prices = new double[5];4142 Arrays.fill(prices, 9.99);43 System.out.println("Prices: " + Arrays.toString(prices));44 System.out.println("\nInitialize grid:");45 int[][] grid = new int[3][4];outputFill entire array: Filled with 42: [42, 42, 42, 42, 42, 42, 42, 42, 42, 42] Fill with zero: Original: [1, 2, 3, 4, 5] Zeroed: [0, 0, 0, 0, 0] Fill range: Filled: [10, 10, 10, 20, 20, 20, 20, 30, 30, 30] Fill strings: Filled: [hello, hello, hello, hello, hello] Fill booleans: All true: [true, true, true, true, true, true, true, true] Middle false: [true, true, false, false, false, false, true, true] Fill doubles: Prices: [9.99, 9.99, 9.99, 9.99, 9.99] Initialize grid:for (int[] row : grid)
pass 1 of 347for (int[] row : grid) {48 Arrays.fill(row, -1);49}System.out.println("Grid initialized to -1:");
51System.out.println("Grid initialized to -1:");52for (int[] row : grid) {outputGrid initialized to -1:for (int[] row : grid)
pass 1 of 351System.out.println("Grid initialized to -1:");52for (int[] row : grid) {53 System.out.println(" " + Arrays.toString(row));54}output [-1, -1, -1, -1]board ← , board[0] ← X, board[4] ← O, board[8] ← X
54}55System.out.println("\nFill sections:");56int[] sections = new int[12];5758Arrays.fill(sections, 0, 4, 1);59Arrays.fill(sections, 4, 8, 2);60Arrays.fill(sections, 8, 12, 3);6162System.out.println("Sections: " + Arrays.toString(sections));63System.out.println("\nReset array:");64int[] scores = {85, 92, 78, 95, 88};65System.out.println("Original scores: " + Arrays.toString(scores));6667Arrays.fill(scores, 0);68System.out.println("Reset scores: " + Arrays.toString(scores));69System.out.println("\nMark positions:");70char[] board→ = new char[9];71Arrays.fill(board→ ---------, '-');72System.out.println("Empty board: " + Arrays.toString(board---------));7374board[0]→ X = 'X';75board[4]→ O = 'O';76board[8]→ X = 'X';77System.out.println("After moves: " + Arrays.toString(boardX---O---X));78System.out.println("\nFill 2D array row-wise:");79int[][] matrix = new int[4][4];output Fill sections: Sections: [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3] Reset array: Original scores: [85, 92, 78, 95, 88] Reset scores: [0, 0, 0, 0, 0] Mark positions: Empty board: [-, -, -, -, -, -, -, -, -] After moves: [X, -, -, -, O, -, -, -, X] Fill 2D array row-wise:for (int i = 0; i < matrix.length; i++)
pass 1 of 481for (int i0 = 0; i < matrix.length4; i++) {82 Arrays.fill(matrix[i], i0 + 1);83}All 4 passes — pass 1 is the card above pass i1 0 2 1 3 2 4 3 System.out.println("Matrix:");
85System.out.println("Matrix:");86for (int[] row : matrix) {outputMatrix:for (int[] row : matrix)
pass 1 of 485System.out.println("Matrix:");86for (int[] row : matrix) {87 System.out.println(" " + Arrays.toString(row));88}output [1, 1, 1, 1]
Comparing Arrays
Check if arrays have equal contents.
Equals.java
Replay: real traced execution (multi-file project)
// Arrays.equals and related methods
import java.util.Arrays;
public class Equals {
public static void main(String[] args) {
System.out.println("Equals basics:");
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {1, 2, 3, 4, 5};
int[] arr3 = {1, 2, 3, 4, 6};
System.out.println("arr1: " + Arrays.toString(arr1));
System.out.println("arr2: " + Arrays.toString(arr2));
System.out.println("arr3: " + Arrays.toString(arr3));
System.out.println("arr1.equals(arr2) [WRONG]: " + arr1.equals(arr2));
System.out.println("Arrays.equals(arr1, arr2): " + Arrays.equals(arr1, arr2));
System.out.println("Arrays.equals(arr1, arr3): " + Arrays.equals(arr1, arr3));
System.out.println("\nDifferent lengths:");
int[] short1 = {1, 2, 3};
int[] long1 = {1, 2, 3, 4, 5};
System.out.println("short: " + Arrays.toString(short1));
System.out.println("long: " + Arrays.toString(long1));
System.out.println("Equal? " + Arrays.equals(short1, long1));
System.out.println("\nString arrays:");
String[] words1 = {"hello", "world"};
String[] words2 = {"hello", "world"};
String[] words3 = {"Hello", "World"};
System.out.println("words1: " + Arrays.toString(words1));
System.out.println("words2: " + Arrays.toString(words2));
System.out.println("words3: " + Arrays.toString(words3));
System.out.println("words1 == words2: " + Arrays.equals(words1, words2));
System.out.println("words1 == words3: " + Arrays.equals(words1, words3));
System.out.println("\nNull handling:");
int[] notNull = {1, 2, 3};
int[] alsoNull = null;
System.out.println("Arrays.equals(null, null): " + Arrays.equals(alsoNull, alsoNull));
System.out.println("Arrays.equals(arr, null): " + Arrays.equals(notNull, alsoNull));
System.out.println("\nDeepEquals for 2D arrays:");
int[][] matrix1 = {{1, 2}, {3, 4}};
int[][] matrix2 = {{1, 2}, {3, 4}};
int[][] matrix3 = {{1, 2}, {3, 5}};
System.out.println("matrix1: " + Arrays.deepToString(matrix1));
System.out.println("matrix2: " + Arrays.deepToString(matrix2));
System.out.println("matrix3: " + Arrays.deepToString(matrix3));
System.out.println("Arrays.equals (WRONG): " + Arrays.equals(matrix1, matrix2));
System.out.println("Arrays.deepEquals: " + Arrays.deepEquals(matrix1, matrix2));
System.out.println("matrix1 vs matrix3: " + Arrays.deepEquals(matrix1, matrix3));
System.out.println("\nCompare (lexicographic):");
int[] nums1 = {1, 2, 3};
int[] nums2 = {1, 2, 4};
int[] nums3 = {1, 2, 3, 4};
System.out.println("nums1: " + Arrays.toString(nums1));
System.out.println("nums2: " + Arrays.toString(nums2));
System.out.println("nums3: " + Arrays.toString(nums3));
System.out.println("compare(nums1, nums2): " + Arrays.compare(nums1, nums2));
System.out.println("compare(nums2, nums1): " + Arrays.compare(nums2, nums1));
System.out.println("compare(nums1, nums3): " + Arrays.compare(nums1, nums3));
System.out.println("\nMismatch:");
int[] a = {1, 2, 3, 4, 5};
int[] b = {1, 2, 9, 4, 5};
int[] c = {1, 2, 3, 4, 5};
System.out.println("a: " + Arrays.toString(a));
System.out.println("b: " + Arrays.toString(b));
System.out.println("c: " + Arrays.toString(c));
System.out.println("mismatch(a, b): " + Arrays.mismatch(a, b));
System.out.println("mismatch(a, c): " + Arrays.mismatch(a, c));
System.out.println("\nHashCode:");
int[] hash1 = {1, 2, 3};
int[] hash2 = {1, 2, 3};
int[] hash3 = {3, 2, 1};
System.out.println("hash1: " + Arrays.hashCode(hash1));
System.out.println("hash2: " + Arrays.hashCode(hash2));
System.out.println("hash3: " + Arrays.hashCode(hash3));
System.out.println("Same hashCode? " + (Arrays.hashCode(hash1) == Arrays.hashCode(hash2)));
System.out.println("\nDeep hash:");
int[][] deep1 = {{1, 2}, {3, 4}};
int[][] deep2 = {{1, 2}, {3, 4}};
System.out.println("deepHashCode(deep1): " + Arrays.deepHashCode(deep1));
System.out.println("deepHashCode(deep2): " + Arrays.deepHashCode(deep2));
System.out.println("Same? " + (Arrays.deepHashCode(deep1) == Arrays.deepHashCode(deep2)));
System.out.println("\nToString:");
int[] display = {10, 20, 30};
System.out.println("toString: " + Arrays.toString(display));
System.out.println("Regular: " + display); // Object reference
System.out.println("\nDeep toString:");
int[][] matrix = {{1, 2, 3}, {4, 5, 6}};
System.out.println("toString: " + Arrays.toString(matrix));
System.out.println("deepToString: " + Arrays.deepToString(matrix));
}
}
alsoNull ← null
5public class Equals {6 public static void main(String[] args) {7 System.out.println("Equals basics:");8 int[] arr1 = {1, 2, 3, 4, 5};9 int[] arr2 = {1, 2, 3, 4, 5};10 int[] arr3 = {1, 2, 3, 4, 6};1112 System.out.println("arr1: " + Arrays.toString(arr1));13 System.out.println("arr2: " + Arrays.toString(arr2));14 System.out.println("arr3: " + Arrays.toString(arr3));1516 System.out.println("arr1.equals(arr2) [WRONG]: " + arr1.equals(arr2));17 System.out.println("Arrays.equals(arr1, arr2): " + Arrays.equals(arr1, arr2));18 System.out.println("Arrays.equals(arr1, arr3): " + Arrays.equals(arr1, arr3));19 System.out.println("\nDifferent lengths:");20 int[] short1 = {1, 2, 3};21 int[] long1 = {1, 2, 3, 4, 5};2223 System.out.println("short: " + Arrays.toString(short1));24 System.out.println("long: " + Arrays.toString(long1));25 System.out.println("Equal? " + Arrays.equals(short1, long1));26 System.out.println("\nString arrays:");27 String[] words1 = {"hello", "world"};28 String[] words2 = {"hello", "world"};29 String[] words3 = {"Hello", "World"};3031 System.out.println("words1: " + Arrays.toString(words1));32 System.out.println("words2: " + Arrays.toString(words2));33 System.out.println("words3: " + Arrays.toString(words3));3435 System.out.println("words1 == words2: " + Arrays.equals(words1, words2));36 System.out.println("words1 == words3: " + Arrays.equals(words1, words3));37 System.out.println("\nNull handling:");38 int[] notNull = {1, 2, 3};39 int[] alsoNull→ null = null;4041 System.out.println("Arrays.equals(null, null): " + Arrays.equals(alsoNullnull, alsoNull));42 System.out.println("Arrays.equals(arr, null): " + Arrays.equals(notNull, alsoNullnull));43 System.out.println("\nDeepEquals for 2D arrays:");44 int[][] matrix1 = {{1, 2}, {3, 4}};45 int[][] matrix2 = {{1, 2}, {3, 4}};46 int[][] matrix3 = {{1, 2}, {3, 5}};4748 System.out.println("matrix1: " + Arrays.deepToString(matrix1));49 System.out.println("matrix2: " + Arrays.deepToString(matrix2));50 System.out.println("matrix3: " + Arrays.deepToString(matrix3));5152 System.out.println("Arrays.equals (WRONG): " + Arrays.equals(matrix1, matrix2));53 System.out.println("Arrays.deepEquals: " + Arrays.deepEquals(matrix1, matrix2));54 System.out.println("matrix1 vs matrix3: " + Arrays.deepEquals(matrix1, matrix3));55 System.out.println("\nCompare (lexicographic):");56 int[] nums1 = {1, 2, 3};57 int[] nums2 = {1, 2, 4};58 int[] nums3 = {1, 2, 3, 4};5960 System.out.println("nums1: " + Arrays.toString(nums1));61 System.out.println("nums2: " + Arrays.toString(nums2));62 System.out.println("nums3: " + Arrays.toString(nums3));6364 System.out.println("compare(nums1, nums2): " + Arrays.compare(nums1, nums2));65 System.out.println("compare(nums2, nums1): " + Arrays.compare(nums2, nums1));66 System.out.println("compare(nums1, nums3): " + Arrays.compare(nums1, nums3));67 System.out.println("\nMismatch:");68 int[] a = {1, 2, 3, 4, 5};69 int[] b = {1, 2, 9, 4, 5};70 int[] c = {1, 2, 3, 4, 5};7172 System.out.println("a: " + Arrays.toString(a));73 System.out.println("b: " + Arrays.toString(b));74 System.out.println("c: " + Arrays.toString(c));7576 System.out.println("mismatch(a, b): " + Arrays.mismatch(a, b));77 System.out.println("mismatch(a, c): " + Arrays.mismatch(a, c));78 System.out.println("\nHashCode:");79 int[] hash1 = {1, 2, 3};80 int[] hash2 = {1, 2, 3};81 int[] hash3 = {3, 2, 1};8283 System.out.println("hash1: " + Arrays.hashCode(hash1));84 System.out.println("hash2: " + Arrays.hashCode(hash2));85 System.out.println("hash3: " + Arrays.hashCode(hash3));86 System.out.println("Same hashCode? " + (Arrays.hashCode(hash1) == Arrays.hashCode(hash2)));87 System.out.println("\nDeep hash:");88 int[][] deep1 = {{1, 2}, {3, 4}};89 int[][] deep2 = {{1, 2}, {3, 4}};9091 System.out.println("deepHashCode(deep1): " + Arrays.deepHashCode(deep1));92 System.out.println("deepHashCode(deep2): " + Arrays.deepHashCode(deep2));93 System.out.println("Same? " + (Arrays.deepHashCode(deep1) == Arrays.deepHashCode(deep2)));94 System.out.println("\nToString:");95 int[] display = {10, 20, 30};96 System.out.println("toString: " + Arrays.toString(display));97 System.out.println("Regular: " + display); // Object reference98 System.out.println("\nDeep toString:");99 int[][] matrix = {{1, 2, 3}, {4, 5, 6}};100 System.out.println("toString: " + Arrays.toString(matrix));101 System.out.println("deepToString: " + Arrays.deepToString(matrix));102 }outputEquals basics: arr1: [1, 2, 3, 4, 5] arr2: [1, 2, 3, 4, 5] arr3: [1, 2, 3, 4, 6] arr1.equals(arr2) [WRONG]: false Arrays.equals(arr1, arr2): true Arrays.equals(arr1, arr3): false Different lengths: short: [1, 2, 3] long: [1, 2, 3, 4, 5] Equal? false String arrays: words1: [hello, world] words2: [hello, world] words3: [Hello, World] words1 == words2: true words1 == words3: false Null handling: Arrays.equals(null, null): true Arrays.equals(arr, null): false DeepEquals for 2D arrays: matrix1: [[1, 2], [3, 4]] matrix2: [[1, 2], [3, 4]] matrix3: [[1, 2], [3, 5]] Arrays.equals (WRONG): false Arrays.deepEquals: true matrix1 vs matrix3: false Compare (lexicographic): nums1: [1, 2, 3] nums2: [1, 2, 4] nums3: [1, 2, 3, 4] compare(nums1, nums2): -1 compare(nums2, nums1): 1 compare(nums1, nums3): -1 Mismatch: a: [1, 2, 3, 4, 5] b: [1, 2, 9, 4, 5] c: [1, 2, 3, 4, 5] mismatch(a, b): 2 mismatch(a, c): -1 HashCode: hash1: 30817 hash2: 30817 hash3: 32737 Same hashCode? true Deep hash: deepHashCode(deep1): 32833 deepHashCode(deep2): 32833 Same? true ToString: toString: [10, 20, 30] Regular: ⟨int[] A⟩ Deep toString: toString: ⟨int[][] B⟩, ⟨int[] C⟩] deepToString: [[1, 2, 3], [4, 5, 6]]
@seealso collections_util
Deep equals
Use Arrays.deepEquals() for nested arrays or multidimensional arrays to compare contents recursively.
Exercise: Practical.java
Sort student grades and find the median score