Operations on arrays, primitive arrays (like int[]
) and
* primitive wrapper arrays (like Integer[]
).
This class tries to handle null
input gracefully.
* An exception will not be thrown for a null
* array input. However, an Object array that contains a null
* element may throw an exception. Each method documents its behaviour.
Inserts the specified element at the specified position in the array. * Shifts the element currently at that position (if any) and any subsequent * elements to the right (adds one to their indices).
* *This method returns a new array with the same elements of the input * array plus the given element on the specified position. The component * type of the returned array is always the same as that of the input * array.
* *If the input array is null
, a new one element array is returned
* whose component type is the same as the element.
* ArrayUtils.add([1.1f], 0, 2.2f) = [2.2f, 1.1f] * ArrayUtils.add([2.3f, 6.4f], 2, 10.5f) = [2.3f, 6.4f, 10.5f] * ArrayUtils.add([2.6f, 6.7f], 0, -4.8f) = [-4.8f, 2.6f, 6.7f] * ArrayUtils.add([2.9f, 6.0f, 0.3f], 2, 1.0f) = [2.9f, 6.0f, 1.0f, 0.3f] ** * @param array the array to add the element to, may be
null
* @param index the position of the new object
* @param element the object to add
* @return A new array containing the existing elements and the new element
* @throws IndexOutOfBoundsException if the index is out of range
* (index < 0 || index > array.length).
*/
public static float[] add(float[] array, int index, float element) {
return (float[]) add(array, index, new Float(element), Float.TYPE);
}
/**
* Underlying implementation of add(array, index, element) methods.
* The last parameter is the class, which may not equal element.getClass
* for primitives.
*
* @param array the array to add the element to, may be null
* @param index the position of the new object
* @param element the object to add
* @param clss the type of the element being added
* @return A new array containing the existing elements and the new element
*/
private static Object add(Object array, int index, Object element, Class clss) {
if (array == null) {
if (index != 0) {
throw new IndexOutOfBoundsException("Index: " + index + ", Length: 0");
}
Object joinedArray = Array.newInstance(clss, 1);
Array.set(joinedArray, 0, element);
return joinedArray;
}
int length = Array.getLength(array);
if (index > length || index < 0) {
throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length);
}
Object result = Array.newInstance(clss, length + 1);
System.arraycopy(array, 0, result, 0, index);
Array.set(result, index, element);
if (index < length) {
System.arraycopy(array, index, result, index + 1, length - index);
}
return result;
}
}