Arrays

  • An array is a reference type
  • int[] or int[][] is an object
  • When you pass it as an argument, you pass a copy of the reference to the array.

Syntax

  • Java style is preferred
// C-style
int array[];
 
// Java-style
int[] array;

Creation

  • max size of array is slightly less than Integer.MAX_VALUE
// list of elements
int[] array = { 1, 2, 3, 4 };
 
// n = array length
int[] numbers = new int[n];
 
// new keyword with list of elements
var floatNumbers = new float[] { 1.02f, 0.03f, 4f };

Iteration

  • For each loop has limitations:
    • cannot access other indices values
    • cannot modify an array because the variable we use for iterations doesn’t hold the actual array element, only a copy
int[] squares = new int[5];
 
// for-loop
for (int i = 0; i < squares.length; i++) {
    squares[i] = i * i; // set the value by the element index 
}
 
System.out.println(Arrays.toString(squares)); // [0, 1, 4, 9, 16]
 
// for-each loop
for (var num:squares) {
    num = 50; // this does not modify the array
}
 
System.out.println(Arrays.toString(squares)); // [0, 1, 4, 9, 16]

Multi-dimensional arrays

  • You can have jagged array with each row having different columns
int[][] twoDimArray = {
        {0, 0},       // the length is 2
        {1, 2, 3, 4}, // the length is 4
        {3, 3, 3}     // the length is 3
};
 
 
System.out.println(foo instanceof int[][]);

Converting Arrays to ArrayList

  • Fixed size Array List:
    • Conversion allows arrays to be viewed as lists.
    • Conversion returns fixed size list
    • Adding and removing elements throw error
    • Changes made to the array will be visible in the returned list, and changes made to the list will be visible in the array.
  • Avoid Arrays.asList() since it is neither completely immutable nor mutable (since add not supported)
    • Use List.of() which creates immutable list
int[] arr = {1, 2, 3};
var myList = Arrays.asList(arr); // mutable and can cause side effects to arr
var myList2 = List.of(arr); // immutable
  • Independent ArrayList:
String[] stringArray = new String[] { "A", "B", "C", "D" }; 
List stringList = new ArrayList<>(Arrays.asList(stringArray));

Converting ArrayList to Array

List<String> strList = new ArrayList<>();
strList.add("abc");
strList.add("xyz");
strList.add("pqr");
strList.add("mno");
 
String[] strArr = strList.toArray(new String[strList.size()]);

Arrays Utilities

  • java.util.Arrays contains helper utilities
  • Setup
int[] arr = new int[] {1, 2, 3, 4, 5};
String[] strArr = {"A", "B"};
Employee[] employees = { new Employee("Ram"), new Employee("Shyam") };
Employee[][] employeesGrid = {
    { new Employee("Ram"), new Employee("Shyam") },
    { new Employee("Radha"), new Employee("Meera") }
};
 
int[][] grid = {{1, 2}, {3, 4}};

Object Array and Primitive Array supported

  • Arrays.stream(arr)
  • Arrays.stream(T[])
IntStream stream1 = Arrays.stream(arr);
Stream<Employee> stream2 = Arrays.stream(employees);
  • Arrays.fill(arr, value)
  • Arrays.fill(T[], value)
    • All indices will refer the same object instance
// [5, 5, 5, 5]
Arrays.fill(arr, 5);
 
// ["Gyan", "Gyan"]
Arrays.fill(employees, new Employee("Gyan"));
  • Arrays.setAll(arr, generator)
  • Arrays.setAll(T[], generator)
Arrays.setAll(arr, i -> i * 2);
Arrays.setAll(employees, i -> new Employee("Employee_" + i));
  • Arrays.copyOf(arr, newLength)
  • Arrays.copyOf(T[], newLength
// [1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
int[] copyArr = Arrays.copyOf(arr, 10);
 
// ["Ram", "Shyam", null, null, null]
Employee[] copyEmployees = Arrays.copyOf(employees, 5);
  • Arrays.equals(arr1, arr2)
  • Arrays.equals(T[], T[])
    • by default compares references
    • override equals() to check content
Arrays.equals(arr, arr2);
Arrays.equals(employees, employees2);
  • Arrays.deepEquals(arr1, arr2) — multi-dimensional array
  • Arrays.deepEquals(T[], T[]) — multi-dimensional array
    • by default compares references
    • override equals() to check content
Arrays.deepEquals(grid, grid2);
Arrays.deepEquals(employeesGrid, employeesGrid2);
  • Arrays.toString(arr)
  • Arrays.toString(T[])
    • by default prints reference
    • override toString() to print content
// [1, 2, 3, 4, 5]
Arrays.toString(arr);
 
// ["Ram", "Shyam"]
Arrays.toString(employees);
  • Arrays.deepToString(arr) — multi-dimensional array
  • Arrays.deepToString(T[]) — multi-dimensional array
    • by default prints reference
    • override toString() to print content
// [[1, 2], [3, 4]]
Arrays.deepToString(grid);
// [[Ram, Shyam], [Radha, Meera]]
Arrays.deepToString(employeesGrid);

Primitive Array

  • Arrays.sort(arr)
    • does not support custom Comparator
// uses Dual-pivot Quick sort
Arrays.sort(arr);
  • Arrays.binarySearch(arr, target)
    • Array must be sorted first
// index =  0  1  2  3  4
// arr   = [1, 2, 3, 4, 5]
// Binary search will return 2
int index = Arrays.binarySearch(arr, 3);

Object Array

  • Arrays.sort(T[])
    • Elements must implement Comparable and override compareTo()
  • Arrays.sort(T[], Comparator)
Arrays.sort(employees);
Arrays.sort(employees, Comparator.comparing(Employee::getName));
  • Arrays.binarySearch(T[], target)
    • Array must be sorted first
    • Array must implement Comparable and override compareTo()
  • Arrays.binarySearch(T[], target, Comparator)
    • Array must be sorted first
    • Array must use same Comparator during sort operation
Arrays.binarySearch(employees, new Employee("Shyam"));
Arrays.binarySearch(employees,
                        new Employee("Shyam"), 
                        Comparator.comparing(Employee::getName)
);
  • Arrays.asList(T[])
    • creates fixed size array
List<String> list = Arrays.asList(strArr);
 
// Warning!!!!!!
// This creates List<int[]> of size 1 instead of List<Integer>
List<int[]> trap = Arrays.asList(arr);