Lesson Completion
Back to course

Arrays Class: Utility Methods for Arrays

Intermediate
20 minutesβ˜…4.5Java

1. The Hook (The "Byte-Sized" Intro)

In a Nutshell: Arrays class provides static utility methods for manipulating arrays: sort(), binarySearch(), equals(), fill(), copyOf(), and asList() (converts array to List). It's the array equivalent of Collections class. Arrays.asList() is crucial for bridging arrays and collections, but the returned list is fixed-size (can't add/remove).

Think of Swiss Army knife for arrays. Need to sort? Arrays.sort(). Compare? Arrays.equals(). Convert to List? Arrays.asList(). One tool, many operations!


2. Conceptual Clarity (The "Simple" Tier)

πŸ’‘ The Analogy: The Toolbox

  • sort(): Alphabetize files
  • asList(): Convert box into shelf (fixed-size!)
  • copyOf(): Photocopier
  • equals(): Side-by-side comparison

3. Technical Mastery (The "Deep Dive")

Key Methods

MethodPurposeExample
sort(array)Sort in-placeArrays.sort(nums)
binarySearch(array, key)Find index (sorted array)Arrays.binarySearch(nums, 5)
equals(arr1, arr2)Deep comparisonArrays.equals(a, b)
fill(array, value)Fill with valueArrays.fill(arr, 0)
copyOf(array, newLength)Copy arrayArrays.copyOf(arr, 10)
asList(T... elements)Array β†’ List (fixed-size!)Arrays.asList(1, 2, 3)
stream(array)Array β†’ Stream (Java 8+)Arrays.stream(nums)

4. Interactive & Applied Code

java
import java.util.*; public class ArraysDemo { public static void main(String[] args) { // SORT int[] numbers = {5, 2, 8, 1, 9}; Arrays.sort(numbers); System.out.println("Sorted: " + Arrays.toString(numbers)); // [1, 2, 5, 8, 9] // BINARY SEARCH (requires sorted array!) int index = Arrays.binarySearch(numbers, 5); System.out.println("Index of 5: " + index); // 2 // EQUALS (deep comparison) int[] arr1 = {1, 2, 3}; int[] arr2 = {1, 2, 3}; System.out.println("arr1 == arr2: " + (arr1 == arr2)); // false (different refs) System.out.println("Arrays.equals: " + Arrays.equals(arr1, arr2)); // true // FILL int[] arr = new int[5]; Arrays.fill(arr, 7); System.out.println("Filled: " + Arrays.toString(arr)); // [7, 7, 7, 7, 7] // COPYOF (resize) int[] original = {1, 2, 3}; int[] copy = Arrays.copyOf(original, 5); // Expands to size 5 System.out.println("Copy: " + Arrays.toString(copy)); // [1, 2, 3, 0, 0] // asList: CRITICAL GOTCHA! List<Integer> list = Arrays.asList(1, 2, 3); list.set(0, 10); // βœ… Can modify elements // list.add(4); // ❌ UnsupportedOperationException (fixed-size!) System.out.println("asList: " + list); // PROPER way to get mutable List List<Integer> mutableList = new ArrayList<>(Arrays.asList(1, 2, 3)); mutableList.add(4); // βœ… Now you can add! System.out.println("Mutable: " + mutableList); // STREAM (Java 8+) int sum = Arrays.stream(numbers).sum(); System.out.println("Sum: " + sum); // MULTIDIMENSIONAL ARRAYS int[][] matrix1 = {{1, 2}, {3, 4}}; int[][] matrix2 = {{1, 2}, {3, 4}}; System.out.println("Deep equals: " + Arrays.deepEquals(matrix1, matrix2)); // true } }

5. The Comparison & Decision Layer

ScenarioSolution
Fixed-size List from arrayArrays.asList(array)
Mutable List from arraynew ArrayList<>(Arrays.asList(array))
Copy arrayArrays.copyOf() or System.arraycopy()
Compare arraysArrays.equals() (or deepEquals())

6. The "Interview Corner" (The Edge)

The "Killer" Interview Question: "Why does Arrays.asList() return a fixed-size list?" Answer: Arrays.asList() returns a wrapper around the original arrayβ€”not a new ArrayList! The returned list is backed by the array, so:

  • βœ… You CAN modify elements (list.set())
  • ❌ You CANNOT add/remove (list.add()/list.remove())

Structural changes would require resizing the underlying array, which isn't supported.

Pro-Tip: Convert primitive array to List:

java
// ❌ DOESN'T WORK: Boxed as single element! int[] primitives = {1, 2, 3}; List<Integer> list = Arrays.asList(primitives); // ❌ List<int[]> ! // βœ… WORKS: Use Stream (Java 8+) List<Integer> list = Arrays.stream(primitives) .boxed() .collect(Collectors.toList());

Autoboxing doesn't work with varargs!

Topics Covered

Java FundamentalsData Structures

Tags

#java#collections#list#set#map#arraylist#hashmap

Last Updated

2025-02-01