In Java, the Arrays
class is a utility class from the java.util
package that provides a collection of static methods for working with arrays. It helps you perform common tasks like sorting, searching, comparing, filling, and converting arrays to strings without writing all the low-level loops yourself.
Importing
import java.util.Arrays;
Common Methods in Arrays
Here’s a breakdown of the most important ones:
1. Sorting
int[] numbers = {5, 3, 8, 1};
Arrays.sort(numbers); // Sorts in ascending order
System.out.println(Arrays.toString(numbers)); // [1, 3, 5, 8]
- Can sort primitive arrays (
int[]
,double[]
, etc.) and object arrays (String[]
). - For custom sorting, use
Arrays.sort(array, comparator)
.
2. Searching
int[] numbers = {1, 3, 5, 8};
int index = Arrays.binarySearch(numbers, 5); // Works on sorted arrays
System.out.println(index); // 2
- Returns index if found, otherwise
-(insertion_point) - 1
.
3. Converting to String
String[] names = {"Alice", "Bob", "Charlie"};
System.out.println(Arrays.toString(names)); // [Alice, Bob, Charlie]
- For multidimensional arrays, use:
int[][] matrix = {{1, 2}, {3, 4}};
System.out.println(Arrays.deepToString(matrix)); // [[1, 2], [3, 4]]
4. Filling
int[] arr = new int[5];
Arrays.fill(arr, 7); // Fill entire array with 7
System.out.println(Arrays.toString(arr)); // [7, 7, 7, 7, 7]
- Overloaded version lets you fill part of an array.
5. Comparing
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println(Arrays.equals(a, b)); // true
int[][] x = {{1, 2}, {3, 4}};
int[][] y = {{1, 2}, {3, 4}};
System.out.println(Arrays.deepEquals(x, y)); // true
6. Copying
int[] original = {1, 2, 3};
int[] copy = Arrays.copyOf(original, 5); // Extra space filled with zeros
System.out.println(Arrays.toString(copy)); // [1, 2, 3, 0, 0]
Arrays.copyOfRange(array, from, to)
copies a portion.
7. Parallel Sorting (Java 8+)
int[] numbers = {5, 3, 8, 1};
Arrays.parallelSort(numbers);
System.out.println(Arrays.toString(numbers)); // [1, 3, 5, 8]
- Uses multiple threads for large arrays.
Key Notes
Arrays
only works for arrays, not collections likeArrayList
(for those, useCollections
class).- It’s a final class, so you cannot extend it.
- All methods are
static
, so you use them with the class name (e.g.,Arrays.sort(...)
).