Class ArrayUtilities
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
- Immutable common arrays for common use cases, such as
EMPTY_OBJECT_ARRAYandEMPTY_BYTE_ARRAY. - Null-safe utility methods for checking array emptiness, size, and performing operations like shallow copying.
- Support for generic array creation and manipulation, including:
- Combining multiple arrays into a new array (
addAll(T[], T[])). - Removing an item from an array by index (
removeItem(T[], int)). - Creating subsets of an array (
getArraySubset(T[], int, int)).
- Combining multiple arrays into a new array (
- Conversion utilities for working with arrays and collections, such as converting a
Collectionto an array of a specified type (toArray(java.lang.Class<T>, java.util.Collection<?>)).
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 featuresarrayutilities.component.type.validation.enabled=false— Block dangerous system classesarrayutilities.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
- Methods like
isEmpty(java.lang.Object)andsize(java.lang.Object)are optimized for performance but remain null-safe. - Some methods, such as
toArray(java.lang.Class<T>, java.util.Collection<?>)andaddAll(T[], T[]), involve array copying and may incur performance costs for very large arrays.
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 -
Method Summary
Modifier and TypeMethodDescriptionstatic <T> T[]addAll(T[] array1, T[] array2) Adds all the elements of the given arrays into a new array.static <T> T[]Append a single element to an array, returning a new array containing the element.static <T> booleancontains(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> TdeepCopyContainers(T array) 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 ObjectgetElement(Object array, int index) Gets an element from an array at the specified index with optimized handling that is significantly faster thanArray.get(Object, int).static intGets the length of an array with optimized handling that is significantly faster thanArray.getLength(Object).static ObjectgetPrimitiveElement(Object array, int index) Gets an element from a primitive array at the specified index with optimized handling that avoids reflection overhead.static <T> intindexOf(T[] array, T item) Locate the first index ofitemwithinarray.static booleanThis is a null-safe isEmpty check.static booleanisNotEmpty(Object array) Null-safe check whether the given array contains at least one element.static <T> intlastIndexOf(T[] array, T item) Locate the last index ofitemwithinarray.static <T> T[]nullToEmpty(Class<T> componentType, T[] array) Return the supplied array, or an empty array ifnull.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 voidsetElement(Object array, int index, Object element) Sets an element in an array at the specified index with optimized handling that is significantly faster thanArray.set(Object, int, Object).static voidsetPrimitiveElement(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 Objectsstatic intReturns 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 [].
-
Field Details
-
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
-
EMPTY_CLASS_ARRAY
-
-
Method Details
-
isEmpty
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:
but gives you more flexibility, since it checks for all array types.return array == null || array.length == 0;- Parameters:
array- array to check- Returns:
- true if empty or null
-
isNotEmpty
Null-safe check whether the given array contains at least one element.- Parameters:
array- array to check- Returns:
trueif array is non-null and has a positive length
-
size
Returns the size (length) of the specified array in a null-safe manner.If the provided array is
null, this method returns0. Otherwise, it returns the length of the array usinggetLength(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 benull- Returns:
- the size of the array, or
0if the array isnull - See Also:
-
getLength
Gets the length of an array with optimized handling that is significantly faster thanArray.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.lengthaccess with type-specific casting.How it works:
- Reference arrays (Object[], String[], etc.): Uses direct
.lengthaccess with a singleinstanceofcheck - no reflection involved - Primitive arrays (int[], long[], etc.): Uses type-specific casting to access
.lengthdirectly 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:
- Reference arrays (Object[], String[], etc.): Uses direct
-
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
nullifnullarray input.- Type Parameters:
T- the array type- Parameters:
array- the array to shallow clone, may benull- Returns:
- the cloned array,
nullifnullinput
-
nullToEmpty
Return the supplied array, or an empty array ifnull.- Type Parameters:
T- array component type- Parameters:
componentType- the component type for the empty array whenarrayisnullarray- array which may benull- Returns:
- the original array, or a new empty array of the specified type if
arrayisnull
-
createArray
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
Tto avoidClassCastExceptionat runtime. - Heap Pollution: The method is annotated with
SafeVarargsto 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
nullelements. Ifnullvalues 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 theelementsarray isnull
- 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
-
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
array1followed by all the elementsarray2. 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 benullarray2- the second array whose elements are added to the new array, may benull- Returns:
- The new array,
nullifnullarray 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 elementpos- 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- ifposis negative or greater than or equal to the array lengthNullPointerException- if the input array is null
-
addItem
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 whenarrayisnullarray- existing array, may benullitem- element to append- Returns:
- new array with
itemappended
-
indexOf
public static <T> int indexOf(T[] array, T item) Locate the first index ofitemwithinarray.- Type Parameters:
T- array component type- Parameters:
array- array to searchitem- item to locate- Returns:
- index of the item or
-1if not found or array isnull
-
lastIndexOf
public static <T> int lastIndexOf(T[] array, T item) Locate the last index ofitemwithinarray.- Type Parameters:
T- array component type- Parameters:
array- array to searchitem- item to locate- Returns:
- index of the item or
-1if not found or array isnull
-
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 benullitem- the item to find- Returns:
trueif the item exists in the array;falseotherwise
-
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 indexend(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 elementsstart- the initial index of the range, inclusiveend- the final index of the range, exclusive- Returns:
- a new array containing the specified range from the original array
- Throws:
ArrayIndexOutOfBoundsException- ifstartis negative,endis greater than the array length, orstartis greater thanendNullPointerException- if the input array is null- See Also:
-
toArray
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 toCollectionUtilities.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
Gets an element from an array at the specified index with optimized handling that is significantly faster thanArray.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
instanceofcheck - 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 boundsIllegalArgumentException- if the argument is not an arrayNullPointerException- if array is null- See Also:
- Reference arrays (Object[], String[], etc.): Uses direct array access
with a single
-
getPrimitiveElement
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 thanArray.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 theinstanceof 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 boundsIllegalArgumentException- if called with a reference type array or non-arrayNullPointerException- if array is null- See Also:
-
setElement
Sets an element in an array at the specified index with optimized handling that is significantly faster thanArray.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
instanceofcheck - 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 elementelement- 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 mismatchArrayIndexOutOfBoundsException- if the index is out of boundsNullPointerException- if array is null- See Also:
- Reference arrays (Object[], String[], etc.): Uses direct array assignment
with a single
-
setPrimitiveElement
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 thanArray.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 theinstanceof 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 elementelement- 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 arrayArrayIndexOutOfBoundsException- if the index is out of boundsNullPointerException- if array is null- See Also:
-