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

Security Configuration

ArrayUtilities provides configurable security controls to prevent various attack vectors including memory exhaustion, reflection attacks, and array manipulation exploits. All security features are disabled by default for backward compatibility.

Security controls can be enabled via system properties:

  • arrayutilities.security.enabled=false — Master switch for all security features
  • arrayutilities.component.type.validation.enabled=false — Block dangerous system classes
  • arrayutilities.max.array.size=2147483639 — Maximum array size (default=Integer.MAX_VALUE-8 when enabled)
  • arrayutilities.dangerous.class.patterns=java.lang.Runtime,java.lang.ProcessBuilder,... — Comma-separated dangerous class patterns

Security Features

  • Component Type Validation: Prevents creation of arrays with dangerous system classes (Runtime, ProcessBuilder, etc.)
  • Array Size Validation: Prevents integer overflow and memory exhaustion through oversized arrays
  • Dangerous Class Filtering: Blocks array creation for security-sensitive classes
  • Error Message Sanitization: Prevents information disclosure in error messages

Usage Example


 // Enable security with custom limits
 System.setProperty("arrayutilities.security.enabled", "true");
 System.setProperty("arrayutilities.max.array.size", "1000000");
 System.setProperty("arrayutilities.dangerous.classes.validation.enabled", "true");

 // These will now enforce security controls
 String[] array = ArrayUtilities.nullToEmpty(String.class, null);
 

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 (kpartlow@gmail.com), John DeRegnaucourt (jdereg@gmail.com)
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[]
    addItem(Class<T> componentType, T[] array, T item)
    Append a single element to an array, returning a new array containing the element.
    static <T> boolean
    contains(T[] array, T item)
    Determine whether the provided array contains the specified item.
    static <T> T[]
    createArray(T... elements)
    Creates and returns an array containing the provided elements.
    static <T> T
    Creates a deep copy of all container structures (arrays and collections) while preserving references to non-container objects.
    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 Object
    getElement(Object array, int index)
    Gets an element from an array at the specified index with optimized handling that is significantly faster than Array.get(Object, int).
    static int
    Gets the length of an array with optimized handling that is significantly faster than Array.getLength(Object).
    static Object
    getPrimitiveElement(Object array, int index)
    Gets an element from a primitive array at the specified index with optimized handling that avoids reflection overhead.
    static <T> int
    indexOf(T[] array, T item)
    Locate the first index of item within array.
    static boolean
    isEmpty(Object array)
    This is a null-safe isEmpty check.
    static boolean
    Null-safe check whether the given array contains at least one element.
    static <T> int
    lastIndexOf(T[] array, T item)
    Locate the last index of item within array.
    static <T> T[]
    nullToEmpty(Class<T> componentType, T[] array)
    Return the supplied array, or an empty array if null.
    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 void
    setElement(Object array, int index, Object element)
    Sets an element in an array at the specified index with optimized handling that is significantly faster than Array.set(Object, int, Object).
    static void
    setPrimitiveElement(Object array, int index, Object element)
    Sets an element in a primitive array at the specified index with optimized handling that avoids reflection and boxing/unboxing overhead.
    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
    • isNotEmpty

      public static boolean isNotEmpty(Object array)
      Null-safe check whether the given array contains at least one element.
      Parameters:
      array - array to check
      Returns:
      true if array is non-null and has a positive length
    • 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 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
      See Also:
    • getLength

      public static int getLength(Object array)
      Gets the length of an array with optimized handling that is significantly faster than Array.getLength(Object).

      Performance: This method is approximately 5-10x faster than the JDK's Array.getLength() for reference type arrays, and 2-5x faster for primitive arrays. The performance gain comes from avoiding reflection overhead by using direct .length access with type-specific casting.

      How it works:

      • Reference arrays (Object[], String[], etc.): Uses direct .length access with a single instanceof check - no reflection involved
      • Primitive arrays (int[], long[], etc.): Uses type-specific casting to access .length directly on the primitive array

      Usage Example:

      
       // Works with any array type
       String[] strings = {"hello", "world"};
       int len = ArrayUtilities.getLength(strings);  // Returns 2
      
       int[] numbers = {1, 2, 3};
       int len = ArrayUtilities.getLength(numbers);  // Returns 3
      
       // When type is unknown at compile time
       Object unknownArray = getArrayFromSomewhere();
       int length = ArrayUtilities.getLength(unknownArray);
       

      When to use: Use this method when the array type is not known at compile time. If you know you have an Object[] at compile time, direct access is still fastest:

      
       // Fastest when type is known at compile time
       Object[] array = ...;
       int length = array.length;
      
       // Use this method when type is unknown
       Object unknownArray = getArrayFromSomewhere();
       int length = ArrayUtilities.getLength(unknownArray);
       
      Parameters:
      array - the array whose length is to be determined (must not be null)
      Returns:
      the length of the array
      Throws:
      IllegalArgumentException - if the argument is not an array
      See Also:
    • 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
    • nullToEmpty

      public static <T> T[] nullToEmpty(Class<T> componentType, T[] array)
      Return the supplied array, or an empty array if null.
      Type Parameters:
      T - array component type
      Parameters:
      componentType - the component type for the empty array when array is null
      array - array which may be null
      Returns:
      the original array, or a new empty array of the specified type if array is null
    • 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.

      Time Complexity: O(n) where n is the array length

      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
    • addItem

      public static <T> T[] addItem(Class<T> componentType, T[] array, T item)
      Append a single element to an array, returning a new array containing the element.
      Type Parameters:
      T - array component type
      Parameters:
      componentType - component type for the array when array is null
      array - existing array, may be null
      item - element to append
      Returns:
      new array with item appended
    • indexOf

      public static <T> int indexOf(T[] array, T item)
      Locate the first index of item within array.
      Type Parameters:
      T - array component type
      Parameters:
      array - array to search
      item - item to locate
      Returns:
      index of the item or -1 if not found or array is null
    • lastIndexOf

      public static <T> int lastIndexOf(T[] array, T item)
      Locate the last index of item within array.
      Type Parameters:
      T - array component type
      Parameters:
      array - array to search
      item - item to locate
      Returns:
      index of the item or -1 if not found or array is null
    • contains

      public static <T> boolean contains(T[] array, T item)
      Determine whether the provided array contains the specified item.
      Type Parameters:
      T - the array component type
      Parameters:
      array - the array to search, may be null
      item - the item to find
      Returns:
      true if the item exists in the array; false otherwise
    • 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'.
    • deepCopyContainers

      public static <T> T deepCopyContainers(T array)
      Creates a deep copy of all container structures (arrays and collections) while preserving references to non-container objects. This method delegates to CollectionUtilities.deepCopyContainers(Object) which performs iterative traversal.

      See CollectionUtilities.deepCopyContainers(Object) for full documentation.

      Type Parameters:
      T - the type of the input array
      Parameters:
      array - the array to deep copy (can contain nested arrays and collections)
      Returns:
      a deep copy of all containers with same references to non-containers, or the same reference if array is not actually an array
      See Also:
    • getElement

      public static Object getElement(Object array, int index)
      Gets an element from an array at the specified index with optimized handling that is significantly faster than Array.get(Object, int).

      Performance: This method is approximately 5-10x faster than the JDK's Array.get() for reference type arrays, and 2-5x faster for primitive arrays. The performance gain comes from avoiding reflection overhead by using direct array access and type-specific casting.

      How it works:

      • Reference arrays (Object[], String[], etc.): Uses direct array access with a single instanceof check - no reflection involved
      • Primitive arrays (int[], long[], etc.): Delegates to getPrimitiveElement(java.lang.Object, int) which uses type-specific casting and returns boxed values

      Usage Example:

      
       // Works with any array type
       String[] strings = {"hello", "world"};
       Object value = ArrayUtilities.getElement(strings, 0);  // Returns "hello"
      
       int[] numbers = {1, 2, 3};
       Object value = ArrayUtilities.getElement(numbers, 0);  // Returns Integer(1)
      
       // When type is unknown at compile time
       Object unknownArray = getArrayFromSomewhere();
       Object element = ArrayUtilities.getElement(unknownArray, index);
       

      When to use: Use this method when the array type is not known at compile time. If you know you have an Object[] at compile time, direct access is still fastest:

      
       // Fastest when type is known at compile time
       Object[] array = ...;
       Object value = array[index];
      
       // Use this method when type is unknown
       Object unknownArray = getArrayFromSomewhere();
       Object value = ArrayUtilities.getElement(unknownArray, index);
       
      Parameters:
      array - the array to read from (must not be null)
      index - the index from which to get the element
      Returns:
      the element at the specified index (primitives are returned as their boxed wrapper types)
      Throws:
      ArrayIndexOutOfBoundsException - if the index is out of bounds
      IllegalArgumentException - if the argument is not an array
      NullPointerException - if array is null
      See Also:
    • getPrimitiveElement

      public static Object getPrimitiveElement(Object array, int index)
      Gets an element from a primitive array at the specified index with optimized handling that avoids reflection overhead. This method is designed for primitive arrays (int[], long[], etc.) and is approximately 2-5x faster than Array.get(Object, int).

      Recommended: For most use cases, prefer getElement(Object, int) which automatically handles both primitive and reference arrays. Use this method directly only when you know you have a primitive array and want to avoid the instanceof Object[] check.

      Performance Characteristics:

      • Primitive arrays: Type-specific casting - ~2-5x faster than Array.get()
      • No instanceof check: Assumes caller has already handled Object[] case
      • JIT-friendly: Type-specific branches allow HotSpot optimization

      Return Values: Primitive values are returned as their corresponding wrapper types (e.g., int returns Integer, boolean returns Boolean).

      Usage Example:

      
       int[] numbers = {1, 2, 3};
       Object value = ArrayUtilities.getPrimitiveElement(numbers, 0);  // Returns Integer(1)
      
       boolean[] flags = {true, false};
       Object value = ArrayUtilities.getPrimitiveElement(flags, 0);  // Returns Boolean.TRUE
       
      Parameters:
      array - the array to read from (must not be null, should be a primitive array)
      index - the index from which to get the element
      Returns:
      the element at the specified index as its boxed wrapper type
      Throws:
      ArrayIndexOutOfBoundsException - if the index is out of bounds
      IllegalArgumentException - if called with a reference type array or non-array
      NullPointerException - if array is null
      See Also:
    • setElement

      public static void setElement(Object array, int index, Object element)
      Sets an element in an array at the specified index with optimized handling that is significantly faster than Array.set(Object, int, Object).

      Performance: This method is approximately 5-10x faster than the JDK's Array.set() for reference type arrays, and 2-5x faster for primitive arrays. The performance gain comes from avoiding reflection overhead by using direct array access and type-specific casting.

      How it works:

      • Reference arrays (Object[], String[], etc.): Uses direct array assignment with a single instanceof check - no reflection involved
      • Primitive arrays (int[], long[], etc.): Delegates to setPrimitiveElement(java.lang.Object, int, java.lang.Object) which uses type-specific casting to avoid boxing/unboxing overhead

      Usage Example:

      
       // Works with any array type
       String[] strings = new String[10];
       ArrayUtilities.setElement(strings, 0, "hello");
      
       int[] numbers = new int[10];
       ArrayUtilities.setElement(numbers, 0, 42);
      
       // Handles null values appropriately
       ArrayUtilities.setElement(strings, 1, null);  // Sets null
       ArrayUtilities.setElement(numbers, 1, null);  // Sets 0 (primitive default)
       

      When to use: Use this method when the array type is not known at compile time, or when you want a single API that handles both primitive and reference arrays efficiently. If you know you have an Object[] at compile time, direct assignment is still fastest:

      
       // Fastest when type is known at compile time
       Object[] array = ...;
       array[index] = value;
      
       // Use this method when type is unknown
       Object unknownArray = getArrayFromSomewhere();
       ArrayUtilities.setElement(unknownArray, index, value);
       
      Parameters:
      array - the array to modify (must not be null)
      index - the index at which to set the element
      element - the element to set (can be null; for primitives, null is converted to default values)
      Throws:
      IllegalArgumentException - if the element cannot be stored in the array due to type mismatch
      ArrayIndexOutOfBoundsException - if the index is out of bounds
      NullPointerException - if array is null
      See Also:
    • setPrimitiveElement

      public static void setPrimitiveElement(Object array, int index, Object element)
      Sets an element in a primitive array at the specified index with optimized handling that avoids reflection and boxing/unboxing overhead. This method is designed for primitive arrays (int[], long[], etc.) and is approximately 2-5x faster than Array.set(Object, int, Object).

      Recommended: For most use cases, prefer setElement(Object, int, Object) which automatically handles both primitive and reference arrays. Use this method directly only when you know you have a primitive array and want to avoid the instanceof Object[] check.

      Performance Characteristics:

      • Primitive arrays: Type-specific casting with no boxing - ~2-5x faster than Array.set()
      • No instanceof check: Assumes caller has already handled Object[] case
      • JIT-friendly: Type-specific branches allow HotSpot optimization

      Primitive Type Handling:

      • Null values are converted to primitive defaults (0, 0L, 0.0, false, '\0', etc.)
      • Direct casting and unboxing to avoid unnecessary object creation
      • Supports all 8 primitive types: boolean, byte, char, short, int, long, float, double

      Usage Example:

      
       // Primitive array - uses type-specific casting
       int[] numbers = new int[10];
       ArrayUtilities.setPrimitiveElement(numbers, 0, 42);
      
       // Handles null values for primitives
       ArrayUtilities.setPrimitiveElement(numbers, 1, null);  // Sets to 0
      
       // When type is unknown at compile time, prefer setElement()
       Object array = getArrayFromSomewhere();
       ArrayUtilities.setElement(array, index, value);  // Handles both cases
       
      Parameters:
      array - the array to modify (must not be null, should be a primitive array)
      index - the index at which to set the element
      element - the element to set (can be null for primitives, converted to default values)
      Throws:
      IllegalArgumentException - if the element cannot be stored in the array due to type mismatch, or if called with a reference type array
      ArrayIndexOutOfBoundsException - if the index is out of bounds
      NullPointerException - if array is null
      See Also: