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_ARRAY
andEMPTY_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
Collection
to an array of a specified type (toArray(java.lang.Class<T>, java.util.Collection<?>)
).
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 ([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 -
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> 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[]
getArraySubset
(T[] array, int start, int end) Creates a new array containing elements from the specified range of the source array.static <T> int
indexOf
(T[] array, T item) Locate the first index ofitem
withinarray
.static boolean
This is a null-safe isEmpty check.static boolean
isNotEmpty
(Object array) Null-safe check whether the given array contains at least one element.static <T> int
lastIndexOf
(T[] array, T item) Locate the last index ofitem
withinarray
.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 <T> T[]
shallowCopy
(T[] array) Shallow copies an array of Objectsstatic int
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 [].
-
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: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:
true
if 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 usingArray.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 benull
- Returns:
- the size of the array, or
0
if the array isnull
-
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
ifnull
array input.- Type Parameters:
T
- the array type- Parameters:
array
- the array to shallow clone, may benull
- Returns:
- the cloned array,
null
ifnull
input
-
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 whenarray
isnull
array
- array which may benull
- Returns:
- the original array, or a new empty array of the specified type if
array
isnull
-
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
T
to avoidClassCastException
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. Ifnull
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 theelements
array 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
array1
followed 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 benull
array2
- the second array whose elements are added to the new array, may benull
- Returns:
- The new array,
null
ifnull
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 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
- ifpos
is 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 whenarray
isnull
array
- existing array, may benull
item
- element to append- Returns:
- new array with
item
appended
-
indexOf
public static <T> int indexOf(T[] array, T item) Locate the first index ofitem
withinarray
.- Type Parameters:
T
- array component type- Parameters:
array
- array to searchitem
- item to locate- Returns:
- index of the item or
-1
if not found or array isnull
-
lastIndexOf
public static <T> int lastIndexOf(T[] array, T item) Locate the last index ofitem
withinarray
.- Type Parameters:
T
- array component type- Parameters:
array
- array to searchitem
- item to locate- Returns:
- index of the item or
-1
if 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 benull
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 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
- ifstart
is negative,end
is greater than the array length, orstart
is greater thanend
NullPointerException
- 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'.
-