Class ArrayUtils

java.lang.Object
org.flag4j.util.ArrayUtils

public final class ArrayUtils extends Object

The ArrayUtils class provides a set of utility methods for performing operations on arrays. This includes transformations, comparisons, cumulative operations, validations, and copying.

For other array operations see: ArrayBuilder, ArrayConversions, and ArrayJoiner.

Key Features:

  • Deep comparison and copying of multidimensional arrays.
  • Element-wise operations, including transformations, swaps, and permutations.
  • Efficient searching and validation, including methods for finding unique values, indices, and membership checks.
  • Flattening and reshaping of multidimensional arrays.

Usage Examples


 // Compute the cumulative sum of an integer array
 int[] array = {1, 2, 3, 4};
 int[] cumSumArray = ArrayUtils.cumSum(array, null);

 // Check if two 2D arrays are element-wise equal
 int[][] array1 = {{1, 2}, {3, 4}};
 int[][] array2 = {{1, 2}, {3, 4}};
 boolean isEqual = ArrayUtils.deepEquals2D(array1, array2);

 // Swap elements in an array
 int[] numbers = {1, 2, 3};
 ArrayUtils.swap(numbers, 0, 2); // Result: {3, 2, 1}

 // Find unique values in an array
 int[] values = {1, 2, 2, 3};
 int[] uniqueValues = ArrayUtils.uniqueSorted(values); // Result: {1, 2, 3}

 // Apply a transformation to a numeric array
 double[] data = {1.0, 2.0, 3.0};
 ArrayUtils.applyTransform(data, x -> x * x); // Squares each value in the array
 

Restrictions

  • Multidimensional arrays are expected to be rectangular for all methods in this class. However, this is not explicitly enforced and jagged arrays may cause unexpected behavior.
  • Many methods assume that input arrays are non-null unless explicitly stated otherwise.
  • Sorting is required, but not enforced, for some methods to function correctly, such as contains(int[], int) and findFirstLast(int[], int). Passing non-sorted arrays to such method results in undefined behavior.

Note: This class is a utility class and cannot be instantiated.

See Also:
  • Method Summary

    Modifier and Type
    Method
    Description
    static Complex128[]
    Applies a transform to an array.
    static double[]
    applyTransform(double[] src, UnaryOperator<Double> opp)
    Applies a transform to an array.
    static double[]
    Applies a transform to an array.
    static <T> T[]
    applyTransform(T[] src, UnaryOperator<T> opp)
    Applies a transform to an array.
    static void
    arraycopy(double[] src, int srcPos, Complex128[] dest, int destPos, int length)
    Performs an array copy similar to System.arraycopy(Object, int, Object, int, int) but wraps doubles as complex numbers.
    static void
    arraycopy(float[] src, int srcPos, Complex64[] dest, int destPos, int length)
    Performs an array copy similar to System.arraycopy(Object, int, Object, int, int) but wraps floats as complex numbers.
    static boolean
    contains(double[] arr, double key)
    Checks if an array contains a specified value.
    static boolean[]
    contains(double[] src, double... keys)
    Checks if a set of keys are in an array.
    static boolean
    contains(int[] arr, int key)
    Checks if an array contains a specified value.
    static boolean[]
    contains(int[] src, int... keys)
    Checks if a set of keys is in an array.
    Creates a mapping of unique values in {code arr} to integers such that each unique value is mapped to a unique integer and those integers range from 0 to numUnique(arr) - 1.
    static int[]
    cumSum(int[] src, int[] dest)
    Computes the cumulative sum of the elements of an array.
    static int[][]
    deepCopy2D(int[][] src, int[][] dest)
    Creates a deep copy of a 2D array.
    static boolean
    deepEquals2D(int[][] src1, int[][] src2)
    Checks if two primitive 2D integer arrays are element-wise equal.
    static <T extends Field<T>>
    boolean
    equals(double[] src1, T[] src2)
    Checks if a double array is numerically equal to a complex number array.
    static int[]
    findFirstLast(int[] src, int key)
    Finds the first and last index of a specified key within a sorted array.
    static double[]
    flatten(double[][] src)
    Flattens a two-dimensional array.
    static int[]
    flatten(int[][] src)
    Flattens a two-dimensional array.
    static Complex128[]
    Flattens a two-dimensional array.
    static <T extends Field<T>>
    T[]
    flatten(T[][] src)
    Flattens a two-dimensional array.
    static <T extends Semiring<T>>
    T[]
    flatten(T[][] src)
    Flattens a two-dimensional array.
    static int
    indexOf(int[] arr, int key)
    Finds the fist index of the specified key within an array.
    static Shape
    Infers the shape of a rectangular nD Java array.
    static int
    nDFlatten(Object nDArray, Shape shape, double[] flatArray, int offset)
    Recursively validates the shape of the nD array and flattens it into the provided 1D array.
    static <T> int
    nDFlatten(Object nDArray, Shape shape, T[] flatArray, int offset)
    Recursively validates the shape of the nD array and flattens it into the provided 1D array.
    static boolean
    notContains(int[] src, int key)
    Checks if a key is in an array.
    static int[]
    notInAxes(int[] srcAxes, int dim)
    Given a list of integers, srcAxes, which is a subset of {0, 1, 2, ...., dim-1} in no particular order, compute the integers which are in {0, 1, 2, ...., dim-1} but not in srcAxes.
    static int
    numUnique(double[] arr)
    Counts the number of unique elements in an array.
    static int
    numUnique(int[] arr)
    Counts the number of unique elements in an array.
    static void
    permute(int[] src, int[] indices)
    Swaps elements in an array according to a specified permutation.
    static void
    permuteUnsafe(int[] src, int[] indices)
    Swaps elements in an array according to a specified permutation.
    static int[]
    shift(int shift, int[] indices)
    Shifts all indices in an array by a specified amount.
    static int[]
    shiftRange(int shift, int[] indices, int start, int stop)
    Shifts a range of indices in an array by a specified amount.
    static void
    swap(double[] arr, int i, int j)
    Swaps to elements in an array.
    static void
    swap(int[] arr, int i, int j)
    Swaps to elements in an array.
    static void
    swap(Object[] arr, int i, int j)
    Swaps to elements in an array.
    static double[]
    Flattens a two-dimensional array and unboxes.
    static int[]
    uniqueSorted(int[] src)
    Gets the unique values from an array and sorts them.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Method Details

    • cumSum

      public static int[] cumSum(int[] src, int[] dest)
      Computes the cumulative sum of the elements of an array.
      Parameters:
      src - Source array to compute cumulative sum within.
      dest - Array to store the result of the cumulative sum. May be the same array as src or null.
      Returns:
      If dest != null then a reference to dest is returned. If dest == null then a new array of appropriate size will be constructed and returned.
      Throws:
      IllegalArgumentException - If dest != null && dest.length != src.length.
    • deepEquals2D

      public static boolean deepEquals2D(int[][] src1, int[][] src2)
      Checks if two primitive 2D integer arrays are element-wise equal.
      Parameters:
      src1 - First array in comparison.
      src2 - Second array in comparison.
      Returns:
      The
    • equals

      public static <T extends Field<T>> boolean equals(double[] src1, T[] src2)
      Checks if a double array is numerically equal to a complex number array.
      Parameters:
      src1 - Double array.
      src2 - Complex number array.
      Returns:
      true if all data in src2 have zero imaginary component and real component equal to the corresponding entry in src1; false otherwise.
    • deepCopy2D

      public static int[][] deepCopy2D(int[][] src, int[][] dest)
      Creates a deep copy of a 2D array. Assumes arrays are not jagged.
      Parameters:
      src - Source array to copy.
      dest - Destination array of copy. If null, a new array will be initialized.
      Returns:
      A reference to dest if it was not null. In the case where dest is null, then a new array will be initialized and returned.
      Throws:
      IllegalArgumentException - If the two arrays are not the same shape.
    • arraycopy

      public static void arraycopy(double[] src, int srcPos, Complex128[] dest, int destPos, int length)
      Performs an array copy similar to System.arraycopy(Object, int, Object, int, int) but wraps doubles as complex numbers.
      Parameters:
      src - The source array.
      srcPos - The starting position from which to copy elements of the source array.
      dest - The destination array for the copy.
      destPos - Starting index to place copied elements in the destination array.
      length - The number of array elements to be copied.
      Throws:
      ArrayIndexOutOfBoundsException - If the destPos parameter plus the length parameter exceeds the length of the source array length or the destination array length.
    • arraycopy

      public static void arraycopy(float[] src, int srcPos, Complex64[] dest, int destPos, int length)
      Performs an array copy similar to System.arraycopy(Object, int, Object, int, int) but wraps floats as complex numbers.
      Parameters:
      src - The source array.
      srcPos - The starting position from which to copy elements of the source array.
      dest - The destination array for the copy.
      destPos - Starting index to place copied elements in the destination array.
      length - The number of array elements to be copied.
      Throws:
      ArrayIndexOutOfBoundsException - If the destPos parameter plus the length parameter exceeds the length of the source array length or the destination array length.
    • swap

      public static void swap(int[] arr, int i, int j)
      Swaps to elements in an array. This is done in place.
      Parameters:
      arr - Array to swap elements in. This array is modified.
      i - Index of first value to swap.
      j - Index of second value to swap.
      Throws:
      IndexOutOfBoundsException - If i or j are out of the bounds of arr.
    • permute

      public static void permute(int[] src, int[] indices)
      Swaps elements in an array according to a specified permutation.
      Parameters:
      src - Array to swap elements within.
      indices - Array containing indices of the permutation. If the src array has length N, then the array must be a permutation of {0, 1, 2, ..., N-1}.
      Throws:
      IllegalArgumentException - If indices is not a permutation of {0, 1, 2, ..., N-1}.
    • permuteUnsafe

      public static void permuteUnsafe(int[] src, int[] indices)
      Swaps elements in an array according to a specified permutation. This method should be used with extreme caution as unlike permute(int[], int[]), this method does not verify that indices is a permutation.
      Parameters:
      src - Array to swap elements within.
      indices - Array containing indices of the permutation. If the src array has length N, then the array must be a permutation of {0, 1, 2, ..., N-1}.
    • swap

      public static void swap(double[] arr, int i, int j)
      Swaps to elements in an array. This is done in place.
      Parameters:
      arr - Array to swap elements in. This array is modified.
      i - Index of first value to swap.
      j - Index of second value to swap.
      Throws:
      IndexOutOfBoundsException - If i or j are out of the bounds of arr.
    • swap

      public static void swap(Object[] arr, int i, int j)
      Swaps to elements in an array. This is done in place.
      Parameters:
      arr - Array to swap elements in. This array is modified.
      i - Index of first value to swap.
      j - Index of second value to swap.
      Throws:
      IndexOutOfBoundsException - If i or j are out of the bounds of arr.
    • notContains

      public static boolean notContains(int[] src, int key)
      Checks if a key is in an array.
      Parameters:
      src - Source array. Must be sorted, if not, call Arrays.sort(double[]) first. Otherwise, the behavior of this method is undefined.
      key - Values to check if they are in the source array.
      Returns:
      A boolean describing if the specified key is in the array or not.
    • contains

      public static boolean[] contains(double[] src, double... keys)
      Checks if a set of keys are in an array.
      Parameters:
      src - Source array. Must be sorted, if not, call Arrays.sort(double[]) first. Otherwise, the behavior of this method is undefined.
      keys - Values to check if they are in the source array.
      Returns:
      A boolean array with the same length as keys describing if the associated keys are in the array.
    • contains

      public static boolean[] contains(int[] src, int... keys)
      Checks if a set of keys is in an array.
      Parameters:
      src - Source array. Must be sorted, if not, call Arrays.sort(int[]) first. Otherwise, the behavior of this method is undefined.
      keys - Values to check if they are in the source array.
      Returns:
      A boolean array with the same length as keys describing if the associated keys are in the array.
    • contains

      public static boolean contains(int[] arr, int key)
      Checks if an array contains a specified value. This method assumes that the array is sorted as it uses the binary search algorithm. If the array is not sorted, use Arrays.sort(int[]) first.
      Parameters:
      arr - Array of interest.
      key - Value to check for in the arr array.
      Returns:
      True if the key value is found in the array. False otherwise.
      See Also:
    • contains

      public static boolean contains(double[] arr, double key)
      Checks if an array contains a specified value. This method assumes that the array is sorted as it uses the binary search algorithm. If the array is not sorted, use Arrays.sort(int[]) first.
      Parameters:
      arr - Array of interest.
      key - Value to check for in the arr array.
      Returns:
      True if the key value is found in the array. False otherwise.
      See Also:
    • nDArrayShape

      public static Shape nDArrayShape(Object nDArray)
      Infers the shape of a rectangular nD Java array.
      Parameters:
      nDArray - The nD Java array to infer the shape from.
      Returns:
      The shape of the nD array as a Shape object.
      Throws:
      IllegalArgumentException - If nDArray is not an array or has inconsistent (i.e. non-rectangular) dimensions.
    • nDFlatten

      public static <T> int nDFlatten(Object nDArray, Shape shape, T[] flatArray, int offset)
      Recursively validates the shape of the nD array and flattens it into the provided 1D array.
      Parameters:
      nDArray - The nD array to flatten.
      shape - The expected shape of the nD array.
      flatArray - The 1D array to populate with flattened data.
      offset - The starting index for the current level of recursion.
      Returns:
      The next available index in the flatArray after processing the current nDArray.
      Throws:
      IllegalArgumentException - If the shape of the nD array is inconsistent with the inferred shape.
    • nDFlatten

      public static int nDFlatten(Object nDArray, Shape shape, double[] flatArray, int offset)
      Recursively validates the shape of the nD array and flattens it into the provided 1D array.
      Parameters:
      nDArray - The nD array to flatten.
      shape - The expected shape of the nD array.
      flatArray - The 1D array to populate with flattened data.
      offset - The starting index for the current level of recursion.
      Returns:
      The next available index in the flatArray after processing the current nDArray.
      Throws:
      IllegalArgumentException - If the shape of the nD array is inconsistent with the inferred shape.
    • flatten

      public static int[] flatten(int[][] src)
      Flattens a two-dimensional array.
      Parameters:
      src - Array to flatten.
      Returns:
      The flattened array.
    • flatten

      public static double[] flatten(double[][] src)
      Flattens a two-dimensional array.
      Parameters:
      src - Array to flatten.
      Returns:
      The flattened array.
    • unboxFlatten

      public static double[] unboxFlatten(Double[][] src)
      Flattens a two-dimensional array and unboxes.
      Parameters:
      src - Array to flatten and unbox.
      Returns:
      The flattened array.
    • flatten

      public static Complex128[] flatten(Complex128[][] src)
      Flattens a two-dimensional array.
      Parameters:
      src - Array to flatten.
      Returns:
      The flattened array.
    • flatten

      public static <T extends Field<T>> T[] flatten(T[][] src)
      Flattens a two-dimensional array.
      Parameters:
      src - Array to flatten.
      Returns:
      The flattened array.
    • flatten

      public static <T extends Semiring<T>> T[] flatten(T[][] src)
      Flattens a two-dimensional array.
      Parameters:
      src - Array to flatten.
      Returns:
      The flattened array.
    • notInAxes

      public static int[] notInAxes(int[] srcAxes, int dim)
      Given a list of integers, srcAxes, which is a subset of {0, 1, 2, ...., dim-1} in no particular order, compute the integers which are in {0, 1, 2, ...., dim-1} but not in srcAxes.
      Parameters:
      srcAxes - Source axes which contains a subset of {0, 1, 2, ...., dim-1} in no particular order.
      dim - Dimension of space which contains the axes of interest.
      Returns:
      An array containing the set subtraction {0, 1, 2, ...., dim-1} - srcAxes.
    • shift

      public static int[] shift(int shift, int[] indices)
      Shifts all indices in an array by a specified amount.
      Parameters:
      shift - Amount to shift indices by.
      indices - Array of indices to shift.
      Returns:
      A reference to indices.
      See Also:
    • shiftRange

      public static int[] shiftRange(int shift, int[] indices, int start, int stop)
      Shifts a range of indices in an array by a specified amount.
      Parameters:
      shift - Amount to shift indices by.
      indices - Array of indices to shift.
      start - Starting index of range to shift (inclusive).
      stop - Stopping index of range to shift (exclusive).
      Returns:
      A reference to indices.
      Throws:
      ArrayIndexOutOfBoundsException - If start or stop is not within the bounds of the indices array.
      See Also:
    • uniqueSorted

      public static int[] uniqueSorted(int[] src)
      Gets the unique values from an array and sorts them.
      Parameters:
      src - The array to get unique values from.
      Returns:
      A sorted array containing all unique values in the src array.
    • indexOf

      public static int indexOf(int[] arr, int key)
      Finds the fist index of the specified key within an array. If the element does not exist, then -1 is returned.
      Parameters:
      arr - Array of interest.
      key - Key value to search for.
      Returns:
      Returns the first index of the value key within the arr array. If the key does not occur in the array, -1 will be returned.
    • numUnique

      public static int numUnique(double[] arr)
      Counts the number of unique elements in an array.
      Parameters:
      arr - Array to count unique elements in.
      Returns:
      The number of unique elements in arr.
    • numUnique

      public static int numUnique(int[] arr)
      Counts the number of unique elements in an array.
      Parameters:
      arr - Array to count unique elements in.
      Returns:
      The number of unique elements in arr.
    • createUniqueMapping

      public static HashMap<Integer,Integer> createUniqueMapping(int[] arr)
      Creates a mapping of unique values in {code arr} to integers such that each unique value is mapped to a unique integer and those integers range from 0 to numUnique(arr) - 1.
      Parameters:
      arr - Array to create a mapping for.
      Returns:
      A mapping of unique values in {code arr} to integers such that each unique value is mapped to a unique integer and those integers range from 0 to numUnique(arr) - 1.
    • findFirstLast

      public static int[] findFirstLast(int[] src, int key)
      Finds the first and last index of a specified key within a sorted array.
      Parameters:
      src - The source array to search within. This array is assumed ot be sorted. If the array is not sorted, call Arrays.sort(src) before this method. If this is not done, and an unsorted array is passed to this method, the results are undefined.
      key - The key value to find the first and last index of within the src array.
      Returns:
      An array of length 2 containing the first (inclusive) and last (exclusive) index of the key within the src array. If the key value does not exist in the array, then both first and last index will be (-insertion_point - 1) where insertion_point is defined as the index the key would be inserted into the sorted array.
    • applyTransform

      public static double[] applyTransform(double[] src, UnaryOperator<Double> opp)
      Applies a transform to an array. This is done in place.
      Parameters:
      src - Array to apply transform to. Modified.
      opp - Operation to use to transform the array.
      Returns:
      A reference to the src array.
    • applyTransform

      public static <T> T[] applyTransform(T[] src, UnaryOperator<T> opp)
      Applies a transform to an array. This is done in place.
      Parameters:
      src - Array to apply transform to. Modified.
      opp - Operation to use to transform the array.
      Returns:
      A reference to the src array.
    • applyTransform

      public static Complex128[] applyTransform(double[] src, Function<Double,Complex128> opp)
      Applies a transform to an array. Note, unlike applyTransform(double[], UnaryOperator) and applyTransform(Object[], UnaryOperator), this method does not work in place.
      Parameters:
      src - Array to apply transform to.
      opp - Operation to use to transform the array.
      Returns:
      A new array containing the result of the transformation.
      See Also:
    • applyTransform

      public static double[] applyTransform(Complex128[] src, Function<Complex128,Double> opp)
      Applies a transform to an array. Note, unlike applyTransform(double[], UnaryOperator) and applyTransform(Object[], UnaryOperator), this method does not work in place.
      Parameters:
      src - Array to apply transform to.
      opp - Operation to use to transform the array.
      Returns:
      A new array containing the result of the transformation.
      See Also: