From 6e112a159f865a4c85732bf1ea3a28a56cd97cad Mon Sep 17 00:00:00 2001 From: Jeff Martin Date: Wed, 1 Sep 2021 19:49:14 -0500 Subject: [PATCH] ArrayUtils: Added add(double[], double) --- src/snap/util/ArrayUtils.java | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/snap/util/ArrayUtils.java b/src/snap/util/ArrayUtils.java index 902e8562..1f29c413 100644 --- a/src/snap/util/ArrayUtils.java +++ b/src/snap/util/ArrayUtils.java @@ -144,6 +144,33 @@ public static T[] removeId(T anArray[], T anObj) return index>=0 ? remove(anArray, index) : anArray; } + /** + * Returns new double array by adding given value to given array. + */ + public static double[] add(double[] anArray, double anObj) { return add(anArray, anObj, anArray.length); } + + /** + * Returns new double array by adding given value to given array at given index. + */ + public static double[] add(double[] anArray, double anObj, int anIndex) + { + // Get array length (throw exception if index out of bounds) + int length = anArray.length; + if (anIndex < 0 || anIndex > length) + throw new ArrayIndexOutOfBoundsException(anIndex); + + // Copy array with extra space + double[] newArray = Arrays.copyOf(anArray, length + 1); + + // Copy elements prior to index, add value at index, and copy elements beyond index + newArray[anIndex] = anObj; + if (anIndex < length) + System.arraycopy(anArray, anIndex, newArray, anIndex + 1, length - anIndex); + + // Return new array + return newArray; + } + /** * Returns the number of object in array of a given class. */