Array Methods

Arrays are fundamental in Java, and understanding their operations and methods simplifies data handling. Java’s Arrays class provides additional functionalities to manage arrays efficiently.

Method Description Example
Arrays.sort(arr) Sorts the array in ascending order Arrays.sort(arr);
Arrays.binarySearch(arr, key) Searches for a key in a sorted array (Binary Search) Arrays.binarySearch(arr, 20);
Arrays.fill(arr, value) Fills the entire array with a specific value Arrays.fill(arr, 5);
Arrays.copyOf(arr, newLength) Copies an array to a new length int[] newArr = Arrays.copyOf(arr, 5);
Arrays.copyOfRange(arr, from, to) Copies a range of elements from an array int[] subArr = Arrays.copyOfRange(arr, 1, 4);
Arrays.toString(arr) Converts an array into a string representation System.out.println(Arrays.toString(arr));
Arrays.equals(arr1, arr2) Compares two arrays for equality Arrays.equals(arr1, arr2);
Arrays.deepEquals(arr1, arr2) Compares multi-dimensional arrays for equality Arrays.deepEquals(arr1, arr2);
Arrays.asList(arr) Converts an array to a List (only for objects) List<String> list = Arrays.asList(arr);
Arrays.hashCode(arr) Returns hash code of the array int hash = Arrays.hashCode(arr);
Arrays.deepHashCode(arr) Returns hash code for multi-dimensional arrays int hash = Arrays.deepHashCode(arr);
Arrays.stream(arr) Converts array to a stream for operations IntStream stream = Arrays.stream(arr);
Arrays.setAll(arr, i -> i * 2) Modifies elements based on a lambda function Arrays.setAll(arr, i -> i * 2);
Arrays.parallelSort(arr) Sorts large arrays using parallel sorting Arrays.parallelSort(arr);
Arrays.spliterator(arr) Creates a Spliterator for an array Spliterator<Integer> s = Arrays.spliterator(arr);