Class ArrayUtilities

java.lang.Object
com.cedarsoftware.util.ArrayUtilities

public final class ArrayUtilities extends Object
A utility class that provides various static methods for working with Java arrays.

ArrayUtilities simplifies common array operations, such as checking for emptiness, combining arrays, creating subsets, and converting collections to arrays. It includes methods that are null-safe and type-generic, making it a flexible and robust tool for array manipulation in Java.

Key Features

Usage Examples


 // Check if an array is empty
 boolean isEmpty = ArrayUtilities.isEmpty(new String[] {});

 // Combine two arrays
 String[] combined = ArrayUtilities.addAll(new String[] {"a", "b"}, new String[] {"c", "d"});

 // Create a subset of an array
 int[] subset = ArrayUtilities.getArraySubset(new int[] {1, 2, 3, 4, 5}, 1, 4); // {2, 3, 4}

 // Convert a collection to a typed array
 List<String> list = List.of("x", "y", "z");
 String[] array = ArrayUtilities.toArray(String.class, list);
 

Performance Notes

Design Philosophy

This utility class is designed to simplify array operations in a type-safe and null-safe manner. It avoids duplicating functionality already present in the JDK while extending support for generic and collection-based workflows.

Author:
Ken Partlow ([email protected]), John DeRegnaucourt ([email protected])
Copyright (c) Cedar Software LLC

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

License

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    static final byte[]
     
    static final char[]
     
    static final Character[]
     
    static final Class<?>[]
     
    static final Object[]
    Immutable common arrays.
  • Method Summary

    Modifier and Type
    Method
    Description
    static <T> T[]
    addAll(T[] array1, T[] array2)
    Adds all the elements of the given arrays into a new array.
    static <T> T[]
    createArray(T... elements)
    Creates and returns an array containing the provided elements.
    static <T> T[]
    getArraySubset(T[] array, int start, int end)
    Creates a new array containing elements from the specified range of the source array.
    static boolean
    isEmpty(Object array)
    This is a null-safe isEmpty check.
    static <T> T[]
    removeItem(T[] array, int pos)
    Removes an element at the specified position from an array, returning a new array with the element removed.
    static <T> T[]
    shallowCopy(T[] array)
    Shallow copies an array of Objects
    static int
    size(Object array)
    Returns the size (length) of the specified array in a null-safe manner.
    static <T> T[]
    toArray(Class<T> classToCastTo, Collection<?> c)
    Convert Collection to a Java (typed) array [].

    Methods inherited from class java.lang.Object

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

    • EMPTY_OBJECT_ARRAY

      public static final Object[] EMPTY_OBJECT_ARRAY
      Immutable common arrays.
    • EMPTY_BYTE_ARRAY

      public static final byte[] EMPTY_BYTE_ARRAY
    • EMPTY_CHAR_ARRAY

      public static final char[] EMPTY_CHAR_ARRAY
    • EMPTY_CHARACTER_ARRAY

      public static final Character[] EMPTY_CHARACTER_ARRAY
    • EMPTY_CLASS_ARRAY

      public static final Class<?>[] EMPTY_CLASS_ARRAY
  • Method Details

    • isEmpty

      public static boolean isEmpty(Object array)
      This is a null-safe isEmpty check. It uses the Array static class for doing a length check. This check is actually .0001 ms slower than the following typed check:

      return array == null || array.length == 0;

      but gives you more flexibility, since it checks for all array types.
      Parameters:
      array - array to check
      Returns:
      true if empty or null
    • size

      public static int size(Object array)
      Returns the size (length) of the specified array in a null-safe manner.

      If the provided array is null, this method returns 0. Otherwise, it returns the length of the array using Array.getLength(Object).

      Usage Example

      
       int[] numbers = {1, 2, 3};
       int size = ArrayUtilities.size(numbers); // size == 3
      
       int sizeOfNull = ArrayUtilities.size(null); // sizeOfNull == 0
       
      Parameters:
      array - the array whose size is to be determined, may be null
      Returns:
      the size of the array, or 0 if the array is null
    • shallowCopy

      public static <T> T[] shallowCopy(T[] array)

      Shallow copies an array of Objects

      The objects in the array are not cloned, thus there is no special handling for multidimensional arrays.

      This method returns null if null array input.

      Type Parameters:
      T - the array type
      Parameters:
      array - the array to shallow clone, may be null
      Returns:
      the cloned array, null if null input
    • createArray

      @SafeVarargs public static <T> T[] createArray(T... elements)
      Creates and returns an array containing the provided elements.

      This method accepts a variable number of arguments and returns them as an array of type T[]. It is primarily used to facilitate array creation in generic contexts, where type inference is necessary.

      Example Usage:

      
       String[] stringArray = createArray("Apple", "Banana", "Cherry");
       Integer[] integerArray = createArray(1, 2, 3, 4);
       Person[] personArray = createArray(new Person("Alice"), new Person("Bob"));
       

      Important Considerations:

      • Type Safety: Due to type erasure in Java generics, this method does not perform any type checks beyond what is already enforced by the compiler. Ensure that all elements are of the expected type T to avoid ClassCastException at runtime.
      • Heap Pollution: The method is annotated with SafeVarargs to suppress warnings related to heap pollution when using generics with varargs. It is safe to use because the method does not perform any unsafe operations on the varargs parameter.
      • Null Elements: The method does not explicitly handle null elements. If null values are passed, they will be included in the returned array.
      Type Parameters:
      T - the component type of the array
      Parameters:
      elements - the elements to be stored in the array
      Returns:
      an array containing the provided elements
      Throws:
      NullPointerException - if the elements array is null
    • addAll

      public static <T> T[] addAll(T[] array1, T[] array2)

      Adds all the elements of the given arrays into a new array.

      The new array contains all the element of array1 followed by all the elements array2. When an array is returned, it is always a new array.

       ArrayUtilities.addAll(null, null)     = null
       ArrayUtilities.addAll(array1, null)   = cloned copy of array1
       ArrayUtilities.addAll(null, array2)   = cloned copy of array2
       ArrayUtilities.addAll([], [])         = []
       ArrayUtilities.addAll([null], [null]) = [null, null]
       ArrayUtilities.addAll(["a", "b", "c"], ["1", "2", "3"]) = ["a", "b", "c", "1", "2", "3"]
       
      Type Parameters:
      T - the array type
      Parameters:
      array1 - the first array whose elements are added to the new array, may be null
      array2 - the second array whose elements are added to the new array, may be null
      Returns:
      The new array, null if null array inputs. The type of the new array is the type of the first array.
    • removeItem

      public static <T> T[] removeItem(T[] array, int pos)
      Removes an element at the specified position from an array, returning a new array with the element removed.

      This method creates a new array with length one less than the input array and copies all elements except the one at the specified position. The original array remains unchanged.

      Example:

      
       Integer[] numbers = {1, 2, 3, 4, 5};
       Integer[] result = ArrayUtilities.removeItem(numbers, 2);
       // result = {1, 2, 4, 5}
       
      Type Parameters:
      T - the component type of the array
      Parameters:
      array - the source array from which to remove an element
      pos - the position of the element to remove (zero-based)
      Returns:
      a new array containing all elements from the original array except the element at the specified position
      Throws:
      ArrayIndexOutOfBoundsException - if pos is negative or greater than or equal to the array length
      NullPointerException - if the input array is null
    • getArraySubset

      public static <T> T[] getArraySubset(T[] array, int start, int end)
      Creates a new array containing elements from the specified range of the source array.

      Returns a new array containing elements from index start (inclusive) to index end (exclusive). The original array remains unchanged.

      Example:

      
       String[] words = {"apple", "banana", "cherry", "date", "elderberry"};
       String[] subset = ArrayUtilities.getArraySubset(words, 1, 4);
       // subset = {"banana", "cherry", "date"}
       
      Type Parameters:
      T - the component type of the array
      Parameters:
      array - the source array from which to extract elements
      start - the initial index of the range, inclusive
      end - the final index of the range, exclusive
      Returns:
      a new array containing the specified range from the original array
      Throws:
      ArrayIndexOutOfBoundsException - if start is negative, end is greater than the array length, or start is greater than end
      NullPointerException - if the input array is null
      See Also:
    • toArray

      public static <T> T[] toArray(Class<T> classToCastTo, Collection<?> c)
      Convert Collection to a Java (typed) array [].
      Type Parameters:
      T - Type of the array
      Parameters:
      classToCastTo - array type (Object[], Person[], etc.)
      c - Collection containing items to be placed into the array.
      Returns:
      Array of the type (T) containing the items from collection 'c'.