Skip to content

Array utils

ljacqu edited this page Aug 20, 2023 · 1 revision

Delegation to methods in Arrays

The Arrays class of the JDK has many methods for dealing with arrays, such as:

Arrays#hashCode(boolean[])
Arrays#hashCode(byte[])
Arrays#hashCode(short[])
...
Arrays#hashCode(Object[])

Arrays whose component is a primitive type are not assignable to Object[], so if you deal with multiple array types, you can only type the array as Object. If you want to call a method on Arrays, you are thus forced to perform instanceof checks to call the right method:

Object numbers = new float[]{ 3.1f, 4.1f, 8.2f };

int hashCode;
if (numbers instanceof byte[]) {
    hashCode = Arrays.hashCode((byte[]) numbers);
} else if (numbers instanceof short[]) {
    hashCode = Arrays.hashCode((short[]) numbers);
// ...
} else if (numbers instanceof float[]) {
    hashCode = Arrays.hashCode((float[]) numbers);
}
// etc.

ArrayUtils circumvents this by checking the array type for you and delegating to the proper method:

int hashCode = ArrayUtils.hashCode(numbers);

Additionally, there is no method in Arrays for sorting and searching in boolean[] arrays. ArrayUtils provides these implementations so that ArrayUtils#binarySearch and ArrayUtils#sort also support all array types.

Stream from array

As another convenience, ArrayUtils provides ArrayUtils#stream which will create a stream over the array's entries, boxing them:

Object numbers = new float[]{ 3.1f, 4.1f, 8.2f };

ArrayUtils.stream(numbers)
    .filter(...)
    .toList();

Note that this method auto-boxes all array entries, so more specific approaches may be favorable if performance is important.

Array type properties

Given a Type, ArrayTypeUtils#getArrayProperty returns an object describing the type's array properties: the component type, and the dimension. For example:

Class<?> clazz = float[][].class;

ArrayTypeProperties properties = ArrayTypeUtils.getArrayProperty(clazz);
System.out.println("Component: " + properties.getComponentType()); // Component: float
System.out.println("Dimension: " + properties.getDimension());     // Dimension: 2

This method also supports generic array types like T[] or List<String>[].

Home

Documentation

  1. Array utils
  2. ClassUtils
  3. Number types

Internal (for development)

  1. Performing a release
  2. Terminology
Clone this wiki locally