T[] subarray(T[] array, int startIndexInclusive, int endIndexExclusive) {
+ if (array == null) {
+ return null;
+ }
+ if (startIndexInclusive < 0) {
+ startIndexInclusive = 0;
+ }
+ if (endIndexExclusive > array.length) {
+ endIndexExclusive = array.length;
+ }
+ int newSize = endIndexExclusive - startIndexInclusive;
+ Class> type = array.getClass().getComponentType();
+ if (newSize <= 0) {
+ @SuppressWarnings("unchecked") // OK, because array is of type T
+ final T[] emptyArray = (T[]) Array.newInstance(type, 0);
+ return emptyArray;
+ }
+ @SuppressWarnings("unchecked") // OK, because array is of type T
+ T[] subarray = (T[]) Array.newInstance(type, newSize);
+ System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
+ return subarray;
+ }
+
+ /**
+ * Produces a new {@code long} array containing the elements
+ * between the start and end indices.
+ *
+ * The start index is inclusive, the end index exclusive.
+ * Null array input produces null output.
+ *
+ * @param array the array
+ * @param startIndexInclusive the starting index. Undervalue (<0)
+ * is promoted to 0, overvalue (>array.length) results
+ * in an empty array.
+ * @param endIndexExclusive elements up to endIndex-1 are present in the
+ * returned subarray. Undervalue (< startIndex) produces
+ * empty array, overvalue (>array.length) is demoted to
+ * array length.
+ * @return a new array containing the elements between
+ * the start and end indices.
+ * @since 2.1
+ */
+ public static long[] subarray(long[] array, int startIndexInclusive, int endIndexExclusive) {
+ if (array == null) {
+ return null;
+ }
+ if (startIndexInclusive < 0) {
+ startIndexInclusive = 0;
+ }
+ if (endIndexExclusive > array.length) {
+ endIndexExclusive = array.length;
+ }
+ int newSize = endIndexExclusive - startIndexInclusive;
+ if (newSize <= 0) {
+ return EMPTY_LONG_ARRAY;
+ }
+
+ long[] subarray = new long[newSize];
+ System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
+ return subarray;
+ }
+
+ /**
+ * Produces a new {@code int} array containing the elements
+ * between the start and end indices.
+ *
+ * The start index is inclusive, the end index exclusive.
+ * Null array input produces null output.
+ *
+ * @param array the array
+ * @param startIndexInclusive the starting index. Undervalue (<0)
+ * is promoted to 0, overvalue (>array.length) results
+ * in an empty array.
+ * @param endIndexExclusive elements up to endIndex-1 are present in the
+ * returned subarray. Undervalue (< startIndex) produces
+ * empty array, overvalue (>array.length) is demoted to
+ * array length.
+ * @return a new array containing the elements between
+ * the start and end indices.
+ * @since 2.1
+ */
+ public static int[] subarray(int[] array, int startIndexInclusive, int endIndexExclusive) {
+ if (array == null) {
+ return null;
+ }
+ if (startIndexInclusive < 0) {
+ startIndexInclusive = 0;
+ }
+ if (endIndexExclusive > array.length) {
+ endIndexExclusive = array.length;
+ }
+ int newSize = endIndexExclusive - startIndexInclusive;
+ if (newSize <= 0) {
+ return EMPTY_INT_ARRAY;
+ }
+
+ int[] subarray = new int[newSize];
+ System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
+ return subarray;
+ }
+
+ /**
+ * Produces a new {@code short} array containing the elements
+ * between the start and end indices.
+ *
+ * The start index is inclusive, the end index exclusive.
+ * Null array input produces null output.
+ *
+ * @param array the array
+ * @param startIndexInclusive the starting index. Undervalue (<0)
+ * is promoted to 0, overvalue (>array.length) results
+ * in an empty array.
+ * @param endIndexExclusive elements up to endIndex-1 are present in the
+ * returned subarray. Undervalue (< startIndex) produces
+ * empty array, overvalue (>array.length) is demoted to
+ * array length.
+ * @return a new array containing the elements between
+ * the start and end indices.
+ * @since 2.1
+ */
+ public static short[] subarray(short[] array, int startIndexInclusive, int endIndexExclusive) {
+ if (array == null) {
+ return null;
+ }
+ if (startIndexInclusive < 0) {
+ startIndexInclusive = 0;
+ }
+ if (endIndexExclusive > array.length) {
+ endIndexExclusive = array.length;
+ }
+ int newSize = endIndexExclusive - startIndexInclusive;
+ if (newSize <= 0) {
+ return EMPTY_SHORT_ARRAY;
+ }
+
+ short[] subarray = new short[newSize];
+ System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
+ return subarray;
+ }
+
+ /**
+ * Produces a new {@code char} array containing the elements
+ * between the start and end indices.
+ *
+ * The start index is inclusive, the end index exclusive.
+ * Null array input produces null output.
+ *
+ * @param array the array
+ * @param startIndexInclusive the starting index. Undervalue (<0)
+ * is promoted to 0, overvalue (>array.length) results
+ * in an empty array.
+ * @param endIndexExclusive elements up to endIndex-1 are present in the
+ * returned subarray. Undervalue (< startIndex) produces
+ * empty array, overvalue (>array.length) is demoted to
+ * array length.
+ * @return a new array containing the elements between
+ * the start and end indices.
+ * @since 2.1
+ */
+ public static char[] subarray(char[] array, int startIndexInclusive, int endIndexExclusive) {
+ if (array == null) {
+ return null;
+ }
+ if (startIndexInclusive < 0) {
+ startIndexInclusive = 0;
+ }
+ if (endIndexExclusive > array.length) {
+ endIndexExclusive = array.length;
+ }
+ int newSize = endIndexExclusive - startIndexInclusive;
+ if (newSize <= 0) {
+ return EMPTY_CHAR_ARRAY;
+ }
+
+ char[] subarray = new char[newSize];
+ System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
+ return subarray;
+ }
+
+ /**
+ * Produces a new {@code byte} array containing the elements
+ * between the start and end indices.
+ *
+ * The start index is inclusive, the end index exclusive.
+ * Null array input produces null output.
+ *
+ * @param array the array
+ * @param startIndexInclusive the starting index. Undervalue (<0)
+ * is promoted to 0, overvalue (>array.length) results
+ * in an empty array.
+ * @param endIndexExclusive elements up to endIndex-1 are present in the
+ * returned subarray. Undervalue (< startIndex) produces
+ * empty array, overvalue (>array.length) is demoted to
+ * array length.
+ * @return a new array containing the elements between
+ * the start and end indices.
+ * @since 2.1
+ */
+ public static byte[] subarray(byte[] array, int startIndexInclusive, int endIndexExclusive) {
+ if (array == null) {
+ return null;
+ }
+ if (startIndexInclusive < 0) {
+ startIndexInclusive = 0;
+ }
+ if (endIndexExclusive > array.length) {
+ endIndexExclusive = array.length;
+ }
+ int newSize = endIndexExclusive - startIndexInclusive;
+ if (newSize <= 0) {
+ return EMPTY_BYTE_ARRAY;
+ }
+
+ byte[] subarray = new byte[newSize];
+ System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
+ return subarray;
+ }
+
+ /**
+ * Produces a new {@code double} array containing the elements
+ * between the start and end indices.
+ *
+ * The start index is inclusive, the end index exclusive.
+ * Null array input produces null output.
+ *
+ * @param array the array
+ * @param startIndexInclusive the starting index. Undervalue (<0)
+ * is promoted to 0, overvalue (>array.length) results
+ * in an empty array.
+ * @param endIndexExclusive elements up to endIndex-1 are present in the
+ * returned subarray. Undervalue (< startIndex) produces
+ * empty array, overvalue (>array.length) is demoted to
+ * array length.
+ * @return a new array containing the elements between
+ * the start and end indices.
+ * @since 2.1
+ */
+ public static double[] subarray(double[] array, int startIndexInclusive, int endIndexExclusive) {
+ if (array == null) {
+ return null;
+ }
+ if (startIndexInclusive < 0) {
+ startIndexInclusive = 0;
+ }
+ if (endIndexExclusive > array.length) {
+ endIndexExclusive = array.length;
+ }
+ int newSize = endIndexExclusive - startIndexInclusive;
+ if (newSize <= 0) {
+ return EMPTY_DOUBLE_ARRAY;
+ }
+
+ double[] subarray = new double[newSize];
+ System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
+ return subarray;
+ }
+
+ /**
+ * Produces a new {@code float} array containing the elements
+ * between the start and end indices.
+ *
+ * The start index is inclusive, the end index exclusive.
+ * Null array input produces null output.
+ *
+ * @param array the array
+ * @param startIndexInclusive the starting index. Undervalue (<0)
+ * is promoted to 0, overvalue (>array.length) results
+ * in an empty array.
+ * @param endIndexExclusive elements up to endIndex-1 are present in the
+ * returned subarray. Undervalue (< startIndex) produces
+ * empty array, overvalue (>array.length) is demoted to
+ * array length.
+ * @return a new array containing the elements between
+ * the start and end indices.
+ * @since 2.1
+ */
+ public static float[] subarray(float[] array, int startIndexInclusive, int endIndexExclusive) {
+ if (array == null) {
+ return null;
+ }
+ if (startIndexInclusive < 0) {
+ startIndexInclusive = 0;
+ }
+ if (endIndexExclusive > array.length) {
+ endIndexExclusive = array.length;
+ }
+ int newSize = endIndexExclusive - startIndexInclusive;
+ if (newSize <= 0) {
+ return EMPTY_FLOAT_ARRAY;
+ }
+
+ float[] subarray = new float[newSize];
+ System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
+ return subarray;
+ }
+
+ /**
+ * Produces a new {@code boolean} array containing the elements
+ * between the start and end indices.
+ *
+ * The start index is inclusive, the end index exclusive.
+ * Null array input produces null output.
+ *
+ * @param array the array
+ * @param startIndexInclusive the starting index. Undervalue (<0)
+ * is promoted to 0, overvalue (>array.length) results
+ * in an empty array.
+ * @param endIndexExclusive elements up to endIndex-1 are present in the
+ * returned subarray. Undervalue (< startIndex) produces
+ * empty array, overvalue (>array.length) is demoted to
+ * array length.
+ * @return a new array containing the elements between
+ * the start and end indices.
+ * @since 2.1
+ */
+ public static boolean[] subarray(boolean[] array, int startIndexInclusive, int endIndexExclusive) {
+ if (array == null) {
+ return null;
+ }
+ if (startIndexInclusive < 0) {
+ startIndexInclusive = 0;
+ }
+ if (endIndexExclusive > array.length) {
+ endIndexExclusive = array.length;
+ }
+ int newSize = endIndexExclusive - startIndexInclusive;
+ if (newSize <= 0) {
+ return EMPTY_BOOLEAN_ARRAY;
+ }
+
+ boolean[] subarray = new boolean[newSize];
+ System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
+ return subarray;
+ }
+
+ // Is same length
+ //-----------------------------------------------------------------------
+ /**
+ * Checks whether two arrays are the same length, treating
+ * {@code null} arrays as length {@code 0}.
+ *
+ *
Any multi-dimensional aspects of the arrays are ignored.
+ *
+ * @param array1 the first array, may be {@code null}
+ * @param array2 the second array, may be {@code null}
+ * @return {@code true} if length of arrays matches, treating
+ * {@code null} as an empty array
+ */
+ public static boolean isSameLength(Object[] array1, Object[] array2) {
+ if ((array1 == null && array2 != null && array2.length > 0) ||
+ (array2 == null && array1 != null && array1.length > 0) ||
+ (array1 != null && array2 != null && array1.length != array2.length)) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Checks whether two arrays are the same length, treating
+ * {@code null} arrays as length {@code 0}.
+ *
+ * @param array1 the first array, may be {@code null}
+ * @param array2 the second array, may be {@code null}
+ * @return {@code true} if length of arrays matches, treating
+ * {@code null} as an empty array
+ */
+ public static boolean isSameLength(long[] array1, long[] array2) {
+ if ((array1 == null && array2 != null && array2.length > 0) ||
+ (array2 == null && array1 != null && array1.length > 0) ||
+ (array1 != null && array2 != null && array1.length != array2.length)) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Checks whether two arrays are the same length, treating
+ * {@code null} arrays as length {@code 0}.
+ *
+ * @param array1 the first array, may be {@code null}
+ * @param array2 the second array, may be {@code null}
+ * @return {@code true} if length of arrays matches, treating
+ * {@code null} as an empty array
+ */
+ public static boolean isSameLength(int[] array1, int[] array2) {
+ if ((array1 == null && array2 != null && array2.length > 0) ||
+ (array2 == null && array1 != null && array1.length > 0) ||
+ (array1 != null && array2 != null && array1.length != array2.length)) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Checks whether two arrays are the same length, treating
+ * {@code null} arrays as length {@code 0}.
+ *
+ * @param array1 the first array, may be {@code null}
+ * @param array2 the second array, may be {@code null}
+ * @return {@code true} if length of arrays matches, treating
+ * {@code null} as an empty array
+ */
+ public static boolean isSameLength(short[] array1, short[] array2) {
+ if ((array1 == null && array2 != null && array2.length > 0) ||
+ (array2 == null && array1 != null && array1.length > 0) ||
+ (array1 != null && array2 != null && array1.length != array2.length)) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Checks whether two arrays are the same length, treating
+ * {@code null} arrays as length {@code 0}.
+ *
+ * @param array1 the first array, may be {@code null}
+ * @param array2 the second array, may be {@code null}
+ * @return {@code true} if length of arrays matches, treating
+ * {@code null} as an empty array
+ */
+ public static boolean isSameLength(char[] array1, char[] array2) {
+ if ((array1 == null && array2 != null && array2.length > 0) ||
+ (array2 == null && array1 != null && array1.length > 0) ||
+ (array1 != null && array2 != null && array1.length != array2.length)) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Checks whether two arrays are the same length, treating
+ * {@code null} arrays as length {@code 0}.
+ *
+ * @param array1 the first array, may be {@code null}
+ * @param array2 the second array, may be {@code null}
+ * @return {@code true} if length of arrays matches, treating
+ * {@code null} as an empty array
+ */
+ public static boolean isSameLength(byte[] array1, byte[] array2) {
+ if ((array1 == null && array2 != null && array2.length > 0) ||
+ (array2 == null && array1 != null && array1.length > 0) ||
+ (array1 != null && array2 != null && array1.length != array2.length)) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Checks whether two arrays are the same length, treating
+ * {@code null} arrays as length {@code 0}.
+ *
+ * @param array1 the first array, may be {@code null}
+ * @param array2 the second array, may be {@code null}
+ * @return {@code true} if length of arrays matches, treating
+ * {@code null} as an empty array
+ */
+ public static boolean isSameLength(double[] array1, double[] array2) {
+ if ((array1 == null && array2 != null && array2.length > 0) ||
+ (array2 == null && array1 != null && array1.length > 0) ||
+ (array1 != null && array2 != null && array1.length != array2.length)) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Checks whether two arrays are the same length, treating
+ * {@code null} arrays as length {@code 0}.
+ *
+ * @param array1 the first array, may be {@code null}
+ * @param array2 the second array, may be {@code null}
+ * @return {@code true} if length of arrays matches, treating
+ * {@code null} as an empty array
+ */
+ public static boolean isSameLength(float[] array1, float[] array2) {
+ if ((array1 == null && array2 != null && array2.length > 0) ||
+ (array2 == null && array1 != null && array1.length > 0) ||
+ (array1 != null && array2 != null && array1.length != array2.length)) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Checks whether two arrays are the same length, treating
+ * {@code null} arrays as length {@code 0}.
+ *
+ * @param array1 the first array, may be {@code null}
+ * @param array2 the second array, may be {@code null}
+ * @return {@code true} if length of arrays matches, treating
+ * {@code null} as an empty array
+ */
+ public static boolean isSameLength(boolean[] array1, boolean[] array2) {
+ if ((array1 == null && array2 != null && array2.length > 0) ||
+ (array2 == null && array1 != null && array1.length > 0) ||
+ (array1 != null && array2 != null && array1.length != array2.length)) {
+ return false;
+ }
+ return true;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Returns the length of the specified array.
+ * This method can deal with {@code Object} arrays and with primitive arrays.
+ *
+ * If the input array is {@code null}, {@code 0} is returned.
+ *
+ *
+ * ArrayUtils.getLength(null) = 0
+ * ArrayUtils.getLength([]) = 0
+ * ArrayUtils.getLength([null]) = 1
+ * ArrayUtils.getLength([true, false]) = 2
+ * ArrayUtils.getLength([1, 2, 3]) = 3
+ * ArrayUtils.getLength(["a", "b", "c"]) = 3
+ *
+ *
+ * @param array the array to retrieve the length from, may be null
+ * @return The length of the array, or {@code 0} if the array is {@code null}
+ * @throws IllegalArgumentException if the object arguement is not an array.
+ * @since 2.1
+ */
+ public static int getLength(Object array) {
+ if (array == null) {
+ return 0;
+ }
+ return Array.getLength(array);
+ }
+
+ /**
+ * Checks whether two arrays are the same type taking into account
+ * multi-dimensional arrays.
+ *
+ * @param array1 the first array, must not be {@code null}
+ * @param array2 the second array, must not be {@code null}
+ * @return {@code true} if type of arrays matches
+ * @throws IllegalArgumentException if either array is {@code null}
+ */
+ public static boolean isSameType(Object array1, Object array2) {
+ if (array1 == null || array2 == null) {
+ throw new IllegalArgumentException("The Array must not be null");
+ }
+ return array1.getClass().getName().equals(array2.getClass().getName());
+ }
+
+ // Reverse
+ //-----------------------------------------------------------------------
+ /**
+ * Reverses the order of the given array.
+ *
+ * There is no special handling for multi-dimensional arrays.
+ *
+ * This method does nothing for a {@code null} input array.
+ *
+ * @param array the array to reverse, may be {@code null}
+ */
+ public static void reverse(Object[] array) {
+ if (array == null) {
+ return;
+ }
+ int i = 0;
+ int j = array.length - 1;
+ Object tmp;
+ while (j > i) {
+ tmp = array[j];
+ array[j] = array[i];
+ array[i] = tmp;
+ j--;
+ i++;
+ }
+ }
+
+ /**
+ * Reverses the order of the given array.
+ *
+ * This method does nothing for a {@code null} input array.
+ *
+ * @param array the array to reverse, may be {@code null}
+ */
+ public static void reverse(long[] array) {
+ if (array == null) {
+ return;
+ }
+ int i = 0;
+ int j = array.length - 1;
+ long tmp;
+ while (j > i) {
+ tmp = array[j];
+ array[j] = array[i];
+ array[i] = tmp;
+ j--;
+ i++;
+ }
+ }
+
+ /**
+ * Reverses the order of the given array.
+ *
+ * This method does nothing for a {@code null} input array.
+ *
+ * @param array the array to reverse, may be {@code null}
+ */
+ public static void reverse(int[] array) {
+ if (array == null) {
+ return;
+ }
+ int i = 0;
+ int j = array.length - 1;
+ int tmp;
+ while (j > i) {
+ tmp = array[j];
+ array[j] = array[i];
+ array[i] = tmp;
+ j--;
+ i++;
+ }
+ }
+
+ /**
+ * Reverses the order of the given array.
+ *
+ * This method does nothing for a {@code null} input array.
+ *
+ * @param array the array to reverse, may be {@code null}
+ */
+ public static void reverse(short[] array) {
+ if (array == null) {
+ return;
+ }
+ int i = 0;
+ int j = array.length - 1;
+ short tmp;
+ while (j > i) {
+ tmp = array[j];
+ array[j] = array[i];
+ array[i] = tmp;
+ j--;
+ i++;
+ }
+ }
+
+ /**
+ * Reverses the order of the given array.
+ *
+ * This method does nothing for a {@code null} input array.
+ *
+ * @param array the array to reverse, may be {@code null}
+ */
+ public static void reverse(char[] array) {
+ if (array == null) {
+ return;
+ }
+ int i = 0;
+ int j = array.length - 1;
+ char tmp;
+ while (j > i) {
+ tmp = array[j];
+ array[j] = array[i];
+ array[i] = tmp;
+ j--;
+ i++;
+ }
+ }
+
+ /**
+ * Reverses the order of the given array.
+ *
+ * This method does nothing for a {@code null} input array.
+ *
+ * @param array the array to reverse, may be {@code null}
+ */
+ public static void reverse(byte[] array) {
+ if (array == null) {
+ return;
+ }
+ int i = 0;
+ int j = array.length - 1;
+ byte tmp;
+ while (j > i) {
+ tmp = array[j];
+ array[j] = array[i];
+ array[i] = tmp;
+ j--;
+ i++;
+ }
+ }
+
+ /**
+ * Reverses the order of the given array.
+ *
+ * This method does nothing for a {@code null} input array.
+ *
+ * @param array the array to reverse, may be {@code null}
+ */
+ public static void reverse(double[] array) {
+ if (array == null) {
+ return;
+ }
+ int i = 0;
+ int j = array.length - 1;
+ double tmp;
+ while (j > i) {
+ tmp = array[j];
+ array[j] = array[i];
+ array[i] = tmp;
+ j--;
+ i++;
+ }
+ }
+
+ /**
+ * Reverses the order of the given array.
+ *
+ * This method does nothing for a {@code null} input array.
+ *
+ * @param array the array to reverse, may be {@code null}
+ */
+ public static void reverse(float[] array) {
+ if (array == null) {
+ return;
+ }
+ int i = 0;
+ int j = array.length - 1;
+ float tmp;
+ while (j > i) {
+ tmp = array[j];
+ array[j] = array[i];
+ array[i] = tmp;
+ j--;
+ i++;
+ }
+ }
+
+ /**
+ * Reverses the order of the given array.
+ *
+ * This method does nothing for a {@code null} input array.
+ *
+ * @param array the array to reverse, may be {@code null}
+ */
+ public static void reverse(boolean[] array) {
+ if (array == null) {
+ return;
+ }
+ int i = 0;
+ int j = array.length - 1;
+ boolean tmp;
+ while (j > i) {
+ tmp = array[j];
+ array[j] = array[i];
+ array[i] = tmp;
+ j--;
+ i++;
+ }
+ }
+
+ // IndexOf search
+ // ----------------------------------------------------------------------
+
+ // Object IndexOf
+ //-----------------------------------------------------------------------
+ /**
+ * Finds the index of the given object in the array.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * @param array the array to search through for the object, may be {@code null}
+ * @param objectToFind the object to find, may be {@code null}
+ * @return the index of the object within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int indexOf(Object[] array, Object objectToFind) {
+ return indexOf(array, objectToFind, 0);
+ }
+
+ /**
+ * Finds the index of the given object in the array starting at the given index.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * A negative startIndex is treated as zero. A startIndex larger than the array
+ * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).
+ *
+ * @param array the array to search through for the object, may be {@code null}
+ * @param objectToFind the object to find, may be {@code null}
+ * @param startIndex the index to start searching at
+ * @return the index of the object within the array starting at the index,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int indexOf(Object[] array, Object objectToFind, int startIndex) {
+ if (array == null) {
+ return INDEX_NOT_FOUND;
+ }
+ if (startIndex < 0) {
+ startIndex = 0;
+ }
+ if (objectToFind == null) {
+ for (int i = startIndex; i < array.length; i++) {
+ if (array[i] == null) {
+ return i;
+ }
+ }
+ } else if (array.getClass().getComponentType().isInstance(objectToFind)) {
+ for (int i = startIndex; i < array.length; i++) {
+ if (objectToFind.equals(array[i])) {
+ return i;
+ }
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+
+ /**
+ * Finds the last index of the given object within the array.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * @param array the array to travers backwords looking for the object, may be {@code null}
+ * @param objectToFind the object to find, may be {@code null}
+ * @return the last index of the object within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int lastIndexOf(Object[] array, Object objectToFind) {
+ return lastIndexOf(array, objectToFind, Integer.MAX_VALUE);
+ }
+
+ /**
+ * Finds the last index of the given object in the array starting at the given index.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than
+ * the array length will search from the end of the array.
+ *
+ * @param array the array to traverse for looking for the object, may be {@code null}
+ * @param objectToFind the object to find, may be {@code null}
+ * @param startIndex the start index to travers backwards from
+ * @return the last index of the object within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int lastIndexOf(Object[] array, Object objectToFind, int startIndex) {
+ if (array == null) {
+ return INDEX_NOT_FOUND;
+ }
+ if (startIndex < 0) {
+ return INDEX_NOT_FOUND;
+ } else if (startIndex >= array.length) {
+ startIndex = array.length - 1;
+ }
+ if (objectToFind == null) {
+ for (int i = startIndex; i >= 0; i--) {
+ if (array[i] == null) {
+ return i;
+ }
+ }
+ } else if (array.getClass().getComponentType().isInstance(objectToFind)) {
+ for (int i = startIndex; i >= 0; i--) {
+ if (objectToFind.equals(array[i])) {
+ return i;
+ }
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+
+ /**
+ * Checks if the object is in the given array.
+ *
+ * The method returns {@code false} if a {@code null} array is passed in.
+ *
+ * @param array the array to search through
+ * @param objectToFind the object to find
+ * @return {@code true} if the array contains the object
+ */
+ public static boolean contains(Object[] array, Object objectToFind) {
+ return indexOf(array, objectToFind) != INDEX_NOT_FOUND;
+ }
+
+ // long IndexOf
+ //-----------------------------------------------------------------------
+ /**
+ * Finds the index of the given value in the array.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * @param array the array to search through for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @return the index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int indexOf(long[] array, long valueToFind) {
+ return indexOf(array, valueToFind, 0);
+ }
+
+ /**
+ * Finds the index of the given value in the array starting at the given index.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * A negative startIndex is treated as zero. A startIndex larger than the array
+ * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).
+ *
+ * @param array the array to search through for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @param startIndex the index to start searching at
+ * @return the index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int indexOf(long[] array, long valueToFind, int startIndex) {
+ if (array == null) {
+ return INDEX_NOT_FOUND;
+ }
+ if (startIndex < 0) {
+ startIndex = 0;
+ }
+ for (int i = startIndex; i < array.length; i++) {
+ if (valueToFind == array[i]) {
+ return i;
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+
+ /**
+ * Finds the last index of the given value within the array.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * @param array the array to travers backwords looking for the object, may be {@code null}
+ * @param valueToFind the object to find
+ * @return the last index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int lastIndexOf(long[] array, long valueToFind) {
+ return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
+ }
+
+ /**
+ * Finds the last index of the given value in the array starting at the given index.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the
+ * array length will search from the end of the array.
+ *
+ * @param array the array to traverse for looking for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @param startIndex the start index to travers backwards from
+ * @return the last index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int lastIndexOf(long[] array, long valueToFind, int startIndex) {
+ if (array == null) {
+ return INDEX_NOT_FOUND;
+ }
+ if (startIndex < 0) {
+ return INDEX_NOT_FOUND;
+ } else if (startIndex >= array.length) {
+ startIndex = array.length - 1;
+ }
+ for (int i = startIndex; i >= 0; i--) {
+ if (valueToFind == array[i]) {
+ return i;
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+
+ /**
+ * Checks if the value is in the given array.
+ *
+ * The method returns {@code false} if a {@code null} array is passed in.
+ *
+ * @param array the array to search through
+ * @param valueToFind the value to find
+ * @return {@code true} if the array contains the object
+ */
+ public static boolean contains(long[] array, long valueToFind) {
+ return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
+ }
+
+ // int IndexOf
+ //-----------------------------------------------------------------------
+ /**
+ * Finds the index of the given value in the array.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * @param array the array to search through for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @return the index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int indexOf(int[] array, int valueToFind) {
+ return indexOf(array, valueToFind, 0);
+ }
+
+ /**
+ * Finds the index of the given value in the array starting at the given index.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * A negative startIndex is treated as zero. A startIndex larger than the array
+ * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).
+ *
+ * @param array the array to search through for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @param startIndex the index to start searching at
+ * @return the index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int indexOf(int[] array, int valueToFind, int startIndex) {
+ if (array == null) {
+ return INDEX_NOT_FOUND;
+ }
+ if (startIndex < 0) {
+ startIndex = 0;
+ }
+ for (int i = startIndex; i < array.length; i++) {
+ if (valueToFind == array[i]) {
+ return i;
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+
+ /**
+ * Finds the last index of the given value within the array.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * @param array the array to travers backwords looking for the object, may be {@code null}
+ * @param valueToFind the object to find
+ * @return the last index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int lastIndexOf(int[] array, int valueToFind) {
+ return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
+ }
+
+ /**
+ * Finds the last index of the given value in the array starting at the given index.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the
+ * array length will search from the end of the array.
+ *
+ * @param array the array to traverse for looking for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @param startIndex the start index to travers backwards from
+ * @return the last index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int lastIndexOf(int[] array, int valueToFind, int startIndex) {
+ if (array == null) {
+ return INDEX_NOT_FOUND;
+ }
+ if (startIndex < 0) {
+ return INDEX_NOT_FOUND;
+ } else if (startIndex >= array.length) {
+ startIndex = array.length - 1;
+ }
+ for (int i = startIndex; i >= 0; i--) {
+ if (valueToFind == array[i]) {
+ return i;
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+
+ /**
+ * Checks if the value is in the given array.
+ *
+ * The method returns {@code false} if a {@code null} array is passed in.
+ *
+ * @param array the array to search through
+ * @param valueToFind the value to find
+ * @return {@code true} if the array contains the object
+ */
+ public static boolean contains(int[] array, int valueToFind) {
+ return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
+ }
+
+ // short IndexOf
+ //-----------------------------------------------------------------------
+ /**
+ * Finds the index of the given value in the array.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * @param array the array to search through for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @return the index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int indexOf(short[] array, short valueToFind) {
+ return indexOf(array, valueToFind, 0);
+ }
+
+ /**
+ * Finds the index of the given value in the array starting at the given index.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * A negative startIndex is treated as zero. A startIndex larger than the array
+ * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).
+ *
+ * @param array the array to search through for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @param startIndex the index to start searching at
+ * @return the index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int indexOf(short[] array, short valueToFind, int startIndex) {
+ if (array == null) {
+ return INDEX_NOT_FOUND;
+ }
+ if (startIndex < 0) {
+ startIndex = 0;
+ }
+ for (int i = startIndex; i < array.length; i++) {
+ if (valueToFind == array[i]) {
+ return i;
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+
+ /**
+ * Finds the last index of the given value within the array.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * @param array the array to travers backwords looking for the object, may be {@code null}
+ * @param valueToFind the object to find
+ * @return the last index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int lastIndexOf(short[] array, short valueToFind) {
+ return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
+ }
+
+ /**
+ * Finds the last index of the given value in the array starting at the given index.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the
+ * array length will search from the end of the array.
+ *
+ * @param array the array to traverse for looking for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @param startIndex the start index to travers backwards from
+ * @return the last index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int lastIndexOf(short[] array, short valueToFind, int startIndex) {
+ if (array == null) {
+ return INDEX_NOT_FOUND;
+ }
+ if (startIndex < 0) {
+ return INDEX_NOT_FOUND;
+ } else if (startIndex >= array.length) {
+ startIndex = array.length - 1;
+ }
+ for (int i = startIndex; i >= 0; i--) {
+ if (valueToFind == array[i]) {
+ return i;
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+
+ /**
+ * Checks if the value is in the given array.
+ *
+ * The method returns {@code false} if a {@code null} array is passed in.
+ *
+ * @param array the array to search through
+ * @param valueToFind the value to find
+ * @return {@code true} if the array contains the object
+ */
+ public static boolean contains(short[] array, short valueToFind) {
+ return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
+ }
+
+ // char IndexOf
+ //-----------------------------------------------------------------------
+ /**
+ * Finds the index of the given value in the array.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * @param array the array to search through for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @return the index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ * @since 2.1
+ */
+ public static int indexOf(char[] array, char valueToFind) {
+ return indexOf(array, valueToFind, 0);
+ }
+
+ /**
+ * Finds the index of the given value in the array starting at the given index.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * A negative startIndex is treated as zero. A startIndex larger than the array
+ * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).
+ *
+ * @param array the array to search through for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @param startIndex the index to start searching at
+ * @return the index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ * @since 2.1
+ */
+ public static int indexOf(char[] array, char valueToFind, int startIndex) {
+ if (array == null) {
+ return INDEX_NOT_FOUND;
+ }
+ if (startIndex < 0) {
+ startIndex = 0;
+ }
+ for (int i = startIndex; i < array.length; i++) {
+ if (valueToFind == array[i]) {
+ return i;
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+
+ /**
+ * Finds the last index of the given value within the array.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * @param array the array to travers backwords looking for the object, may be {@code null}
+ * @param valueToFind the object to find
+ * @return the last index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ * @since 2.1
+ */
+ public static int lastIndexOf(char[] array, char valueToFind) {
+ return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
+ }
+
+ /**
+ * Finds the last index of the given value in the array starting at the given index.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the
+ * array length will search from the end of the array.
+ *
+ * @param array the array to traverse for looking for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @param startIndex the start index to travers backwards from
+ * @return the last index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ * @since 2.1
+ */
+ public static int lastIndexOf(char[] array, char valueToFind, int startIndex) {
+ if (array == null) {
+ return INDEX_NOT_FOUND;
+ }
+ if (startIndex < 0) {
+ return INDEX_NOT_FOUND;
+ } else if (startIndex >= array.length) {
+ startIndex = array.length - 1;
+ }
+ for (int i = startIndex; i >= 0; i--) {
+ if (valueToFind == array[i]) {
+ return i;
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+
+ /**
+ * Checks if the value is in the given array.
+ *
+ * The method returns {@code false} if a {@code null} array is passed in.
+ *
+ * @param array the array to search through
+ * @param valueToFind the value to find
+ * @return {@code true} if the array contains the object
+ * @since 2.1
+ */
+ public static boolean contains(char[] array, char valueToFind) {
+ return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
+ }
+
+ // byte IndexOf
+ //-----------------------------------------------------------------------
+ /**
+ * Finds the index of the given value in the array.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * @param array the array to search through for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @return the index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int indexOf(byte[] array, byte valueToFind) {
+ return indexOf(array, valueToFind, 0);
+ }
+
+ /**
+ * Finds the index of the given value in the array starting at the given index.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * A negative startIndex is treated as zero. A startIndex larger than the array
+ * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).
+ *
+ * @param array the array to search through for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @param startIndex the index to start searching at
+ * @return the index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int indexOf(byte[] array, byte valueToFind, int startIndex) {
+ if (array == null) {
+ return INDEX_NOT_FOUND;
+ }
+ if (startIndex < 0) {
+ startIndex = 0;
+ }
+ for (int i = startIndex; i < array.length; i++) {
+ if (valueToFind == array[i]) {
+ return i;
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+
+ /**
+ * Finds the last index of the given value within the array.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * @param array the array to travers backwords looking for the object, may be {@code null}
+ * @param valueToFind the object to find
+ * @return the last index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int lastIndexOf(byte[] array, byte valueToFind) {
+ return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
+ }
+
+ /**
+ * Finds the last index of the given value in the array starting at the given index.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the
+ * array length will search from the end of the array.
+ *
+ * @param array the array to traverse for looking for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @param startIndex the start index to travers backwards from
+ * @return the last index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int lastIndexOf(byte[] array, byte valueToFind, int startIndex) {
+ if (array == null) {
+ return INDEX_NOT_FOUND;
+ }
+ if (startIndex < 0) {
+ return INDEX_NOT_FOUND;
+ } else if (startIndex >= array.length) {
+ startIndex = array.length - 1;
+ }
+ for (int i = startIndex; i >= 0; i--) {
+ if (valueToFind == array[i]) {
+ return i;
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+
+ /**
+ * Checks if the value is in the given array.
+ *
+ * The method returns {@code false} if a {@code null} array is passed in.
+ *
+ * @param array the array to search through
+ * @param valueToFind the value to find
+ * @return {@code true} if the array contains the object
+ */
+ public static boolean contains(byte[] array, byte valueToFind) {
+ return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
+ }
+
+ // double IndexOf
+ //-----------------------------------------------------------------------
+ /**
+ * Finds the index of the given value in the array.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * @param array the array to search through for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @return the index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int indexOf(double[] array, double valueToFind) {
+ return indexOf(array, valueToFind, 0);
+ }
+
+ /**
+ * Finds the index of the given value within a given tolerance in the array.
+ * This method will return the index of the first value which falls between the region
+ * defined by valueToFind - tolerance and valueToFind + tolerance.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * @param array the array to search through for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @param tolerance tolerance of the search
+ * @return the index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int indexOf(double[] array, double valueToFind, double tolerance) {
+ return indexOf(array, valueToFind, 0, tolerance);
+ }
+
+ /**
+ * Finds the index of the given value in the array starting at the given index.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * A negative startIndex is treated as zero. A startIndex larger than the array
+ * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).
+ *
+ * @param array the array to search through for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @param startIndex the index to start searching at
+ * @return the index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int indexOf(double[] array, double valueToFind, int startIndex) {
+ if (ArrayUtils.isEmpty(array)) {
+ return INDEX_NOT_FOUND;
+ }
+ if (startIndex < 0) {
+ startIndex = 0;
+ }
+ for (int i = startIndex; i < array.length; i++) {
+ if (valueToFind == array[i]) {
+ return i;
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+
+ /**
+ * Finds the index of the given value in the array starting at the given index.
+ * This method will return the index of the first value which falls between the region
+ * defined by valueToFind - tolerance and valueToFind + tolerance.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * A negative startIndex is treated as zero. A startIndex larger than the array
+ * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).
+ *
+ * @param array the array to search through for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @param startIndex the index to start searching at
+ * @param tolerance tolerance of the search
+ * @return the index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int indexOf(double[] array, double valueToFind, int startIndex, double tolerance) {
+ if (ArrayUtils.isEmpty(array)) {
+ return INDEX_NOT_FOUND;
+ }
+ if (startIndex < 0) {
+ startIndex = 0;
+ }
+ double min = valueToFind - tolerance;
+ double max = valueToFind + tolerance;
+ for (int i = startIndex; i < array.length; i++) {
+ if (array[i] >= min && array[i] <= max) {
+ return i;
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+
+ /**
+ * Finds the last index of the given value within the array.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * @param array the array to travers backwords looking for the object, may be {@code null}
+ * @param valueToFind the object to find
+ * @return the last index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int lastIndexOf(double[] array, double valueToFind) {
+ return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
+ }
+
+ /**
+ * Finds the last index of the given value within a given tolerance in the array.
+ * This method will return the index of the last value which falls between the region
+ * defined by valueToFind - tolerance and valueToFind + tolerance.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * @param array the array to search through for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @param tolerance tolerance of the search
+ * @return the index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int lastIndexOf(double[] array, double valueToFind, double tolerance) {
+ return lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance);
+ }
+
+ /**
+ * Finds the last index of the given value in the array starting at the given index.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the
+ * array length will search from the end of the array.
+ *
+ * @param array the array to traverse for looking for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @param startIndex the start index to travers backwards from
+ * @return the last index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int lastIndexOf(double[] array, double valueToFind, int startIndex) {
+ if (ArrayUtils.isEmpty(array)) {
+ return INDEX_NOT_FOUND;
+ }
+ if (startIndex < 0) {
+ return INDEX_NOT_FOUND;
+ } else if (startIndex >= array.length) {
+ startIndex = array.length - 1;
+ }
+ for (int i = startIndex; i >= 0; i--) {
+ if (valueToFind == array[i]) {
+ return i;
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+
+ /**
+ * Finds the last index of the given value in the array starting at the given index.
+ * This method will return the index of the last value which falls between the region
+ * defined by valueToFind - tolerance and valueToFind + tolerance.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the
+ * array length will search from the end of the array.
+ *
+ * @param array the array to traverse for looking for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @param startIndex the start index to travers backwards from
+ * @param tolerance search for value within plus/minus this amount
+ * @return the last index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int lastIndexOf(double[] array, double valueToFind, int startIndex, double tolerance) {
+ if (ArrayUtils.isEmpty(array)) {
+ return INDEX_NOT_FOUND;
+ }
+ if (startIndex < 0) {
+ return INDEX_NOT_FOUND;
+ } else if (startIndex >= array.length) {
+ startIndex = array.length - 1;
+ }
+ double min = valueToFind - tolerance;
+ double max = valueToFind + tolerance;
+ for (int i = startIndex; i >= 0; i--) {
+ if (array[i] >= min && array[i] <= max) {
+ return i;
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+
+ /**
+ * Checks if the value is in the given array.
+ *
+ * The method returns {@code false} if a {@code null} array is passed in.
+ *
+ * @param array the array to search through
+ * @param valueToFind the value to find
+ * @return {@code true} if the array contains the object
+ */
+ public static boolean contains(double[] array, double valueToFind) {
+ return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
+ }
+
+ /**
+ * Checks if a value falling within the given tolerance is in the
+ * given array. If the array contains a value within the inclusive range
+ * defined by (value - tolerance) to (value + tolerance).
+ *
+ * The method returns {@code false} if a {@code null} array
+ * is passed in.
+ *
+ * @param array the array to search
+ * @param valueToFind the value to find
+ * @param tolerance the array contains the tolerance of the search
+ * @return true if value falling within tolerance is in array
+ */
+ public static boolean contains(double[] array, double valueToFind, double tolerance) {
+ return indexOf(array, valueToFind, 0, tolerance) != INDEX_NOT_FOUND;
+ }
+
+ // float IndexOf
+ //-----------------------------------------------------------------------
+ /**
+ * Finds the index of the given value in the array.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * @param array the array to search through for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @return the index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int indexOf(float[] array, float valueToFind) {
+ return indexOf(array, valueToFind, 0);
+ }
+
+ /**
+ * Finds the index of the given value in the array starting at the given index.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * A negative startIndex is treated as zero. A startIndex larger than the array
+ * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).
+ *
+ * @param array the array to search through for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @param startIndex the index to start searching at
+ * @return the index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int indexOf(float[] array, float valueToFind, int startIndex) {
+ if (ArrayUtils.isEmpty(array)) {
+ return INDEX_NOT_FOUND;
+ }
+ if (startIndex < 0) {
+ startIndex = 0;
+ }
+ for (int i = startIndex; i < array.length; i++) {
+ if (valueToFind == array[i]) {
+ return i;
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+
+ /**
+ * Finds the last index of the given value within the array.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * @param array the array to travers backwords looking for the object, may be {@code null}
+ * @param valueToFind the object to find
+ * @return the last index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int lastIndexOf(float[] array, float valueToFind) {
+ return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
+ }
+
+ /**
+ * Finds the last index of the given value in the array starting at the given index.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the
+ * array length will search from the end of the array.
+ *
+ * @param array the array to traverse for looking for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @param startIndex the start index to travers backwards from
+ * @return the last index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int lastIndexOf(float[] array, float valueToFind, int startIndex) {
+ if (ArrayUtils.isEmpty(array)) {
+ return INDEX_NOT_FOUND;
+ }
+ if (startIndex < 0) {
+ return INDEX_NOT_FOUND;
+ } else if (startIndex >= array.length) {
+ startIndex = array.length - 1;
+ }
+ for (int i = startIndex; i >= 0; i--) {
+ if (valueToFind == array[i]) {
+ return i;
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+
+ /**
+ * Checks if the value is in the given array.
+ *
+ * The method returns {@code false} if a {@code null} array is passed in.
+ *
+ * @param array the array to search through
+ * @param valueToFind the value to find
+ * @return {@code true} if the array contains the object
+ */
+ public static boolean contains(float[] array, float valueToFind) {
+ return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
+ }
+
+ // boolean IndexOf
+ //-----------------------------------------------------------------------
+ /**
+ * Finds the index of the given value in the array.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * @param array the array to search through for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @return the index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int indexOf(boolean[] array, boolean valueToFind) {
+ return indexOf(array, valueToFind, 0);
+ }
+
+ /**
+ * Finds the index of the given value in the array starting at the given index.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * A negative startIndex is treated as zero. A startIndex larger than the array
+ * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).
+ *
+ * @param array the array to search through for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @param startIndex the index to start searching at
+ * @return the index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null}
+ * array input
+ */
+ public static int indexOf(boolean[] array, boolean valueToFind, int startIndex) {
+ if (ArrayUtils.isEmpty(array)) {
+ return INDEX_NOT_FOUND;
+ }
+ if (startIndex < 0) {
+ startIndex = 0;
+ }
+ for (int i = startIndex; i < array.length; i++) {
+ if (valueToFind == array[i]) {
+ return i;
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+
+ /**
+ * Finds the last index of the given value within the array.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) if
+ * {@code null} array input.
+ *
+ * @param array the array to travers backwords looking for the object, may be {@code null}
+ * @param valueToFind the object to find
+ * @return the last index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int lastIndexOf(boolean[] array, boolean valueToFind) {
+ return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
+ }
+
+ /**
+ * Finds the last index of the given value in the array starting at the given index.
+ *
+ * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ *
+ * A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than
+ * the array length will search from the end of the array.
+ *
+ * @param array the array to traverse for looking for the object, may be {@code null}
+ * @param valueToFind the value to find
+ * @param startIndex the start index to travers backwards from
+ * @return the last index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ public static int lastIndexOf(boolean[] array, boolean valueToFind, int startIndex) {
+ if (ArrayUtils.isEmpty(array)) {
+ return INDEX_NOT_FOUND;
+ }
+ if (startIndex < 0) {
+ return INDEX_NOT_FOUND;
+ } else if (startIndex >= array.length) {
+ startIndex = array.length - 1;
+ }
+ for (int i = startIndex; i >= 0; i--) {
+ if (valueToFind == array[i]) {
+ return i;
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+
+ /**
+ * Checks if the value is in the given array.
+ *
+ * The method returns {@code false} if a {@code null} array is passed in.
+ *
+ * @param array the array to search through
+ * @param valueToFind the value to find
+ * @return {@code true} if the array contains the object
+ */
+ public static boolean contains(boolean[] array, boolean valueToFind) {
+ return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
+ }
+
+ // Primitive/Object array converters
+ // ----------------------------------------------------------------------
+
+ // Character array converters
+ // ----------------------------------------------------------------------
+ /**
+ * Converts an array of object Characters to primitives.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array a {@code Character} array, may be {@code null}
+ * @return a {@code char} array, {@code null} if null array input
+ * @throws NullPointerException if array content is {@code null}
+ */
+ public static char[] toPrimitive(Character[] array) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_CHAR_ARRAY;
+ }
+ final char[] result = new char[array.length];
+ for (int i = 0; i < array.length; i++) {
+ result[i] = array[i].charValue();
+ }
+ return result;
+ }
+
+ /**
+ * Converts an array of object Character to primitives handling {@code null}.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array a {@code Character} array, may be {@code null}
+ * @param valueForNull the value to insert if {@code null} found
+ * @return a {@code char} array, {@code null} if null array input
+ */
+ public static char[] toPrimitive(Character[] array, char valueForNull) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_CHAR_ARRAY;
+ }
+ final char[] result = new char[array.length];
+ for (int i = 0; i < array.length; i++) {
+ Character b = array[i];
+ result[i] = (b == null ? valueForNull : b.charValue());
+ }
+ return result;
+ }
+
+ /**
+ * Converts an array of primitive chars to objects.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array a {@code char} array
+ * @return a {@code Character} array, {@code null} if null array input
+ */
+ public static Character[] toObject(char[] array) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_CHARACTER_OBJECT_ARRAY;
+ }
+ final Character[] result = new Character[array.length];
+ for (int i = 0; i < array.length; i++) {
+ result[i] = Character.valueOf(array[i]);
+ }
+ return result;
+ }
+
+ // Long array converters
+ // ----------------------------------------------------------------------
+ /**
+ * Converts an array of object Longs to primitives.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array a {@code Long} array, may be {@code null}
+ * @return a {@code long} array, {@code null} if null array input
+ * @throws NullPointerException if array content is {@code null}
+ */
+ public static long[] toPrimitive(Long[] array) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_LONG_ARRAY;
+ }
+ final long[] result = new long[array.length];
+ for (int i = 0; i < array.length; i++) {
+ result[i] = array[i].longValue();
+ }
+ return result;
+ }
+
+ /**
+ * Converts an array of object Long to primitives handling {@code null}.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array a {@code Long} array, may be {@code null}
+ * @param valueForNull the value to insert if {@code null} found
+ * @return a {@code long} array, {@code null} if null array input
+ */
+ public static long[] toPrimitive(Long[] array, long valueForNull) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_LONG_ARRAY;
+ }
+ final long[] result = new long[array.length];
+ for (int i = 0; i < array.length; i++) {
+ Long b = array[i];
+ result[i] = (b == null ? valueForNull : b.longValue());
+ }
+ return result;
+ }
+
+ /**
+ * Converts an array of primitive longs to objects.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array a {@code long} array
+ * @return a {@code Long} array, {@code null} if null array input
+ */
+ public static Long[] toObject(long[] array) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_LONG_OBJECT_ARRAY;
+ }
+ final Long[] result = new Long[array.length];
+ for (int i = 0; i < array.length; i++) {
+ result[i] = Long.valueOf(array[i]);
+ }
+ return result;
+ }
+
+ // Int array converters
+ // ----------------------------------------------------------------------
+ /**
+ * Converts an array of object Integers to primitives.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array a {@code Integer} array, may be {@code null}
+ * @return an {@code int} array, {@code null} if null array input
+ * @throws NullPointerException if array content is {@code null}
+ */
+ public static int[] toPrimitive(Integer[] array) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_INT_ARRAY;
+ }
+ final int[] result = new int[array.length];
+ for (int i = 0; i < array.length; i++) {
+ result[i] = array[i].intValue();
+ }
+ return result;
+ }
+
+ /**
+ * Converts an array of object Integer to primitives handling {@code null}.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array a {@code Integer} array, may be {@code null}
+ * @param valueForNull the value to insert if {@code null} found
+ * @return an {@code int} array, {@code null} if null array input
+ */
+ public static int[] toPrimitive(Integer[] array, int valueForNull) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_INT_ARRAY;
+ }
+ final int[] result = new int[array.length];
+ for (int i = 0; i < array.length; i++) {
+ Integer b = array[i];
+ result[i] = (b == null ? valueForNull : b.intValue());
+ }
+ return result;
+ }
+
+ /**
+ * Converts an array of primitive ints to objects.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array an {@code int} array
+ * @return an {@code Integer} array, {@code null} if null array input
+ */
+ public static Integer[] toObject(int[] array) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_INTEGER_OBJECT_ARRAY;
+ }
+ final Integer[] result = new Integer[array.length];
+ for (int i = 0; i < array.length; i++) {
+ result[i] = Integer.valueOf(array[i]);
+ }
+ return result;
+ }
+
+ // Short array converters
+ // ----------------------------------------------------------------------
+ /**
+ * Converts an array of object Shorts to primitives.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array a {@code Short} array, may be {@code null}
+ * @return a {@code byte} array, {@code null} if null array input
+ * @throws NullPointerException if array content is {@code null}
+ */
+ public static short[] toPrimitive(Short[] array) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_SHORT_ARRAY;
+ }
+ final short[] result = new short[array.length];
+ for (int i = 0; i < array.length; i++) {
+ result[i] = array[i].shortValue();
+ }
+ return result;
+ }
+
+ /**
+ * Converts an array of object Short to primitives handling {@code null}.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array a {@code Short} array, may be {@code null}
+ * @param valueForNull the value to insert if {@code null} found
+ * @return a {@code byte} array, {@code null} if null array input
+ */
+ public static short[] toPrimitive(Short[] array, short valueForNull) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_SHORT_ARRAY;
+ }
+ final short[] result = new short[array.length];
+ for (int i = 0; i < array.length; i++) {
+ Short b = array[i];
+ result[i] = (b == null ? valueForNull : b.shortValue());
+ }
+ return result;
+ }
+
+ /**
+ * Converts an array of primitive shorts to objects.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array a {@code short} array
+ * @return a {@code Short} array, {@code null} if null array input
+ */
+ public static Short[] toObject(short[] array) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_SHORT_OBJECT_ARRAY;
+ }
+ final Short[] result = new Short[array.length];
+ for (int i = 0; i < array.length; i++) {
+ result[i] = Short.valueOf(array[i]);
+ }
+ return result;
+ }
+
+ // Byte array converters
+ // ----------------------------------------------------------------------
+ /**
+ * Converts an array of object Bytes to primitives.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array a {@code Byte} array, may be {@code null}
+ * @return a {@code byte} array, {@code null} if null array input
+ * @throws NullPointerException if array content is {@code null}
+ */
+ public static byte[] toPrimitive(Byte[] array) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_BYTE_ARRAY;
+ }
+ final byte[] result = new byte[array.length];
+ for (int i = 0; i < array.length; i++) {
+ result[i] = array[i].byteValue();
+ }
+ return result;
+ }
+
+ /**
+ * Converts an array of object Bytes to primitives handling {@code null}.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array a {@code Byte} array, may be {@code null}
+ * @param valueForNull the value to insert if {@code null} found
+ * @return a {@code byte} array, {@code null} if null array input
+ */
+ public static byte[] toPrimitive(Byte[] array, byte valueForNull) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_BYTE_ARRAY;
+ }
+ final byte[] result = new byte[array.length];
+ for (int i = 0; i < array.length; i++) {
+ Byte b = array[i];
+ result[i] = (b == null ? valueForNull : b.byteValue());
+ }
+ return result;
+ }
+
+ /**
+ * Converts an array of primitive bytes to objects.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array a {@code byte} array
+ * @return a {@code Byte} array, {@code null} if null array input
+ */
+ public static Byte[] toObject(byte[] array) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_BYTE_OBJECT_ARRAY;
+ }
+ final Byte[] result = new Byte[array.length];
+ for (int i = 0; i < array.length; i++) {
+ result[i] = Byte.valueOf(array[i]);
+ }
+ return result;
+ }
+
+ // Double array converters
+ // ----------------------------------------------------------------------
+ /**
+ * Converts an array of object Doubles to primitives.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array a {@code Double} array, may be {@code null}
+ * @return a {@code double} array, {@code null} if null array input
+ * @throws NullPointerException if array content is {@code null}
+ */
+ public static double[] toPrimitive(Double[] array) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_DOUBLE_ARRAY;
+ }
+ final double[] result = new double[array.length];
+ for (int i = 0; i < array.length; i++) {
+ result[i] = array[i].doubleValue();
+ }
+ return result;
+ }
+
+ /**
+ * Converts an array of object Doubles to primitives handling {@code null}.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array a {@code Double} array, may be {@code null}
+ * @param valueForNull the value to insert if {@code null} found
+ * @return a {@code double} array, {@code null} if null array input
+ */
+ public static double[] toPrimitive(Double[] array, double valueForNull) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_DOUBLE_ARRAY;
+ }
+ final double[] result = new double[array.length];
+ for (int i = 0; i < array.length; i++) {
+ Double b = array[i];
+ result[i] = (b == null ? valueForNull : b.doubleValue());
+ }
+ return result;
+ }
+
+ /**
+ * Converts an array of primitive doubles to objects.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array a {@code double} array
+ * @return a {@code Double} array, {@code null} if null array input
+ */
+ public static Double[] toObject(double[] array) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_DOUBLE_OBJECT_ARRAY;
+ }
+ final Double[] result = new Double[array.length];
+ for (int i = 0; i < array.length; i++) {
+ result[i] = Double.valueOf(array[i]);
+ }
+ return result;
+ }
+
+ // Float array converters
+ // ----------------------------------------------------------------------
+ /**
+ * Converts an array of object Floats to primitives.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array a {@code Float} array, may be {@code null}
+ * @return a {@code float} array, {@code null} if null array input
+ * @throws NullPointerException if array content is {@code null}
+ */
+ public static float[] toPrimitive(Float[] array) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_FLOAT_ARRAY;
+ }
+ final float[] result = new float[array.length];
+ for (int i = 0; i < array.length; i++) {
+ result[i] = array[i].floatValue();
+ }
+ return result;
+ }
+
+ /**
+ * Converts an array of object Floats to primitives handling {@code null}.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array a {@code Float} array, may be {@code null}
+ * @param valueForNull the value to insert if {@code null} found
+ * @return a {@code float} array, {@code null} if null array input
+ */
+ public static float[] toPrimitive(Float[] array, float valueForNull) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_FLOAT_ARRAY;
+ }
+ final float[] result = new float[array.length];
+ for (int i = 0; i < array.length; i++) {
+ Float b = array[i];
+ result[i] = (b == null ? valueForNull : b.floatValue());
+ }
+ return result;
+ }
+
+ /**
+ * Converts an array of primitive floats to objects.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array a {@code float} array
+ * @return a {@code Float} array, {@code null} if null array input
+ */
+ public static Float[] toObject(float[] array) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_FLOAT_OBJECT_ARRAY;
+ }
+ final Float[] result = new Float[array.length];
+ for (int i = 0; i < array.length; i++) {
+ result[i] = Float.valueOf(array[i]);
+ }
+ return result;
+ }
+
+ // Boolean array converters
+ // ----------------------------------------------------------------------
+ /**
+ * Converts an array of object Booleans to primitives.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array a {@code Boolean} array, may be {@code null}
+ * @return a {@code boolean} array, {@code null} if null array input
+ * @throws NullPointerException if array content is {@code null}
+ */
+ public static boolean[] toPrimitive(Boolean[] array) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_BOOLEAN_ARRAY;
+ }
+ final boolean[] result = new boolean[array.length];
+ for (int i = 0; i < array.length; i++) {
+ result[i] = array[i].booleanValue();
+ }
+ return result;
+ }
+
+ /**
+ * Converts an array of object Booleans to primitives handling {@code null}.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array a {@code Boolean} array, may be {@code null}
+ * @param valueForNull the value to insert if {@code null} found
+ * @return a {@code boolean} array, {@code null} if null array input
+ */
+ public static boolean[] toPrimitive(Boolean[] array, boolean valueForNull) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_BOOLEAN_ARRAY;
+ }
+ final boolean[] result = new boolean[array.length];
+ for (int i = 0; i < array.length; i++) {
+ Boolean b = array[i];
+ result[i] = (b == null ? valueForNull : b.booleanValue());
+ }
+ return result;
+ }
+
+ /**
+ * Converts an array of primitive booleans to objects.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array a {@code boolean} array
+ * @return a {@code Boolean} array, {@code null} if null array input
+ */
+ public static Boolean[] toObject(boolean[] array) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_BOOLEAN_OBJECT_ARRAY;
+ }
+ final Boolean[] result = new Boolean[array.length];
+ for (int i = 0; i < array.length; i++) {
+ result[i] = (array[i] ? Boolean.TRUE : Boolean.FALSE);
+ }
+ return result;
+ }
+
+ // ----------------------------------------------------------------------
+ /**
+ * Checks if an array of Objects is empty or {@code null}.
+ *
+ * @param array the array to test
+ * @return {@code true} if the array is empty or {@code null}
+ * @since 2.1
+ */
+ public static boolean isEmpty(Object[] array) {
+ return array == null || array.length == 0;
+ }
+
+ /**
+ * Checks if an array of primitive longs is empty or {@code null}.
+ *
+ * @param array the array to test
+ * @return {@code true} if the array is empty or {@code null}
+ * @since 2.1
+ */
+ public static boolean isEmpty(long[] array) {
+ return array == null || array.length == 0;
+ }
+
+ /**
+ * Checks if an array of primitive ints is empty or {@code null}.
+ *
+ * @param array the array to test
+ * @return {@code true} if the array is empty or {@code null}
+ * @since 2.1
+ */
+ public static boolean isEmpty(int[] array) {
+ return array == null || array.length == 0;
+ }
+
+ /**
+ * Checks if an array of primitive shorts is empty or {@code null}.
+ *
+ * @param array the array to test
+ * @return {@code true} if the array is empty or {@code null}
+ * @since 2.1
+ */
+ public static boolean isEmpty(short[] array) {
+ return array == null || array.length == 0;
+ }
+
+ /**
+ * Checks if an array of primitive chars is empty or {@code null}.
+ *
+ * @param array the array to test
+ * @return {@code true} if the array is empty or {@code null}
+ * @since 2.1
+ */
+ public static boolean isEmpty(char[] array) {
+ return array == null || array.length == 0;
+ }
+
+ /**
+ * Checks if an array of primitive bytes is empty or {@code null}.
+ *
+ * @param array the array to test
+ * @return {@code true} if the array is empty or {@code null}
+ * @since 2.1
+ */
+ public static boolean isEmpty(byte[] array) {
+ return array == null || array.length == 0;
+ }
+
+ /**
+ * Checks if an array of primitive doubles is empty or {@code null}.
+ *
+ * @param array the array to test
+ * @return {@code true} if the array is empty or {@code null}
+ * @since 2.1
+ */
+ public static boolean isEmpty(double[] array) {
+ return array == null || array.length == 0;
+ }
+
+ /**
+ * Checks if an array of primitive floats is empty or {@code null}.
+ *
+ * @param array the array to test
+ * @return {@code true} if the array is empty or {@code null}
+ * @since 2.1
+ */
+ public static boolean isEmpty(float[] array) {
+ return array == null || array.length == 0;
+ }
+
+ /**
+ * Checks if an array of primitive booleans is empty or {@code null}.
+ *
+ * @param array the array to test
+ * @return {@code true} if the array is empty or {@code null}
+ * @since 2.1
+ */
+ public static boolean isEmpty(boolean[] array) {
+ return array == null || array.length == 0;
+ }
+
+ // ----------------------------------------------------------------------
+ /**
+ * Checks if an array of Objects is not empty or not {@code null}.
+ *
+ * @param the component type of the array
+ * @param array the array to test
+ * @return {@code true} if the array is not empty or not {@code null}
+ * @since 2.5
+ */
+ public static boolean isNotEmpty(T[] array) {
+ return (array != null && array.length != 0);
+ }
+
+ /**
+ * Checks if an array of primitive longs is not empty or not {@code null}.
+ *
+ * @param array the array to test
+ * @return {@code true} if the array is not empty or not {@code null}
+ * @since 2.5
+ */
+ public static boolean isNotEmpty(long[] array) {
+ return (array != null && array.length != 0);
+ }
+
+ /**
+ * Checks if an array of primitive ints is not empty or not {@code null}.
+ *
+ * @param array the array to test
+ * @return {@code true} if the array is not empty or not {@code null}
+ * @since 2.5
+ */
+ public static boolean isNotEmpty(int[] array) {
+ return (array != null && array.length != 0);
+ }
+
+ /**
+ * Checks if an array of primitive shorts is not empty or not {@code null}.
+ *
+ * @param array the array to test
+ * @return {@code true} if the array is not empty or not {@code null}
+ * @since 2.5
+ */
+ public static boolean isNotEmpty(short[] array) {
+ return (array != null && array.length != 0);
+ }
+
+ /**
+ * Checks if an array of primitive chars is not empty or not {@code null}.
+ *
+ * @param array the array to test
+ * @return {@code true} if the array is not empty or not {@code null}
+ * @since 2.5
+ */
+ public static boolean isNotEmpty(char[] array) {
+ return (array != null && array.length != 0);
+ }
+
+ /**
+ * Checks if an array of primitive bytes is not empty or not {@code null}.
+ *
+ * @param array the array to test
+ * @return {@code true} if the array is not empty or not {@code null}
+ * @since 2.5
+ */
+ public static boolean isNotEmpty(byte[] array) {
+ return (array != null && array.length != 0);
+ }
+
+ /**
+ * Checks if an array of primitive doubles is not empty or not {@code null}.
+ *
+ * @param array the array to test
+ * @return {@code true} if the array is not empty or not {@code null}
+ * @since 2.5
+ */
+ public static boolean isNotEmpty(double[] array) {
+ return (array != null && array.length != 0);
+ }
+
+ /**
+ * Checks if an array of primitive floats is not empty or not {@code null}.
+ *
+ * @param array the array to test
+ * @return {@code true} if the array is not empty or not {@code null}
+ * @since 2.5
+ */
+ public static boolean isNotEmpty(float[] array) {
+ return (array != null && array.length != 0);
+ }
+
+ /**
+ * Checks if an array of primitive booleans is not empty or not {@code null}.
+ *
+ * @param array the array to test
+ * @return {@code true} if the array is not empty or not {@code null}
+ * @since 2.5
+ */
+ public static boolean isNotEmpty(boolean[] array) {
+ return (array != null && array.length != 0);
+ }
+
+ /**
+ * Adds all the elements of the given arrays into a new array.
+ * The new array contains all of the element of {@code array1} followed
+ * by all of the elements {@code array2}. When an array is returned, it is always
+ * a new array.
+ *
+ *
+ * ArrayUtils.addAll(null, null) = null
+ * ArrayUtils.addAll(array1, null) = cloned copy of array1
+ * ArrayUtils.addAll(null, array2) = cloned copy of array2
+ * ArrayUtils.addAll([], []) = []
+ * ArrayUtils.addAll([null], [null]) = [null, null]
+ * ArrayUtils.addAll(["a", "b", "c"], ["1", "2", "3"]) = ["a", "b", "c", "1", "2", "3"]
+ *
+ *
+ * @param the component type of the array
+ * @param array1 the first array whose elements are added to the new array, may be {@code null}
+ * @param array2 the second array whose elements are added to the new array, may be {@code null}
+ * @return The new array, {@code null} if both arrays are {@code null}.
+ * The type of the new array is the type of the first array,
+ * unless the first array is null, in which case the type is the same as the second array.
+ * @since 2.1
+ * @throws IllegalArgumentException if the array types are incompatible
+ */
+ public static T[] addAll(T[] array1, T... array2) {
+ if (array1 == null) {
+ return clone(array2);
+ } else if (array2 == null) {
+ return clone(array1);
+ }
+ final Class> type1 = array1.getClass().getComponentType();
+ @SuppressWarnings("unchecked") // OK, because array is of type T
+ T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length);
+ System.arraycopy(array1, 0, joinedArray, 0, array1.length);
+ try {
+ System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
+ } catch (ArrayStoreException ase) {
+ // Check if problem was due to incompatible types
+ /*
+ * We do this here, rather than before the copy because:
+ * - it would be a wasted check most of the time
+ * - safer, in case check turns out to be too strict
+ */
+ final Class> type2 = array2.getClass().getComponentType();
+ if (!type1.isAssignableFrom(type2)){
+ throw new IllegalArgumentException("Cannot store "+type2.getName()+" in an array of "
+ +type1.getName(), ase);
+ }
+ throw ase; // No, so rethrow original
+ }
+ return joinedArray;
+ }
+
+ /**
+ * Adds all the elements of the given arrays into a new array.
+ * The new array contains all of the element of {@code array1} followed
+ * by all of the elements {@code array2}. When an array is returned, it is always
+ * a new array.
+ *
+ *
+ * ArrayUtils.addAll(array1, null) = cloned copy of array1
+ * ArrayUtils.addAll(null, array2) = cloned copy of array2
+ * ArrayUtils.addAll([], []) = []
+ *
+ *
+ * @param array1 the first array whose elements are added to the new array.
+ * @param array2 the second array whose elements are added to the new array.
+ * @return The new boolean[] array.
+ * @since 2.1
+ */
+ public static boolean[] addAll(boolean[] array1, boolean... array2) {
+ if (array1 == null) {
+ return clone(array2);
+ } else if (array2 == null) {
+ return clone(array1);
+ }
+ boolean[] joinedArray = new boolean[array1.length + array2.length];
+ System.arraycopy(array1, 0, joinedArray, 0, array1.length);
+ System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
+ return joinedArray;
+ }
+
+ /**
+ * Adds all the elements of the given arrays into a new array.
+ * The new array contains all of the element of {@code array1} followed
+ * by all of the elements {@code array2}. When an array is returned, it is always
+ * a new array.
+ *
+ *
+ * ArrayUtils.addAll(array1, null) = cloned copy of array1
+ * ArrayUtils.addAll(null, array2) = cloned copy of array2
+ * ArrayUtils.addAll([], []) = []
+ *
+ *
+ * @param array1 the first array whose elements are added to the new array.
+ * @param array2 the second array whose elements are added to the new array.
+ * @return The new char[] array.
+ * @since 2.1
+ */
+ public static char[] addAll(char[] array1, char... array2) {
+ if (array1 == null) {
+ return clone(array2);
+ } else if (array2 == null) {
+ return clone(array1);
+ }
+ char[] joinedArray = new char[array1.length + array2.length];
+ System.arraycopy(array1, 0, joinedArray, 0, array1.length);
+ System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
+ return joinedArray;
+ }
+
+ /**
+ * Adds all the elements of the given arrays into a new array.
+ * The new array contains all of the element of {@code array1} followed
+ * by all of the elements {@code array2}. When an array is returned, it is always
+ * a new array.
+ *
+ *
+ * ArrayUtils.addAll(array1, null) = cloned copy of array1
+ * ArrayUtils.addAll(null, array2) = cloned copy of array2
+ * ArrayUtils.addAll([], []) = []
+ *
+ *
+ * @param array1 the first array whose elements are added to the new array.
+ * @param array2 the second array whose elements are added to the new array.
+ * @return The new byte[] array.
+ * @since 2.1
+ */
+ public static byte[] addAll(byte[] array1, byte... array2) {
+ if (array1 == null) {
+ return clone(array2);
+ } else if (array2 == null) {
+ return clone(array1);
+ }
+ byte[] joinedArray = new byte[array1.length + array2.length];
+ System.arraycopy(array1, 0, joinedArray, 0, array1.length);
+ System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
+ return joinedArray;
+ }
+
+ /**
+ * Adds all the elements of the given arrays into a new array.
+ * The new array contains all of the element of {@code array1} followed
+ * by all of the elements {@code array2}. When an array is returned, it is always
+ * a new array.
+ *
+ *
+ * ArrayUtils.addAll(array1, null) = cloned copy of array1
+ * ArrayUtils.addAll(null, array2) = cloned copy of array2
+ * ArrayUtils.addAll([], []) = []
+ *
+ *
+ * @param array1 the first array whose elements are added to the new array.
+ * @param array2 the second array whose elements are added to the new array.
+ * @return The new short[] array.
+ * @since 2.1
+ */
+ public static short[] addAll(short[] array1, short... array2) {
+ if (array1 == null) {
+ return clone(array2);
+ } else if (array2 == null) {
+ return clone(array1);
+ }
+ short[] joinedArray = new short[array1.length + array2.length];
+ System.arraycopy(array1, 0, joinedArray, 0, array1.length);
+ System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
+ return joinedArray;
+ }
+
+ /**
+ * Adds all the elements of the given arrays into a new array.
+ * The new array contains all of the element of {@code array1} followed
+ * by all of the elements {@code array2}. When an array is returned, it is always
+ * a new array.
+ *
+ *
+ * ArrayUtils.addAll(array1, null) = cloned copy of array1
+ * ArrayUtils.addAll(null, array2) = cloned copy of array2
+ * ArrayUtils.addAll([], []) = []
+ *
+ *
+ * @param array1 the first array whose elements are added to the new array.
+ * @param array2 the second array whose elements are added to the new array.
+ * @return The new int[] array.
+ * @since 2.1
+ */
+ public static int[] addAll(int[] array1, int... array2) {
+ if (array1 == null) {
+ return clone(array2);
+ } else if (array2 == null) {
+ return clone(array1);
+ }
+ int[] joinedArray = new int[array1.length + array2.length];
+ System.arraycopy(array1, 0, joinedArray, 0, array1.length);
+ System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
+ return joinedArray;
+ }
+
+ /**
+ * Adds all the elements of the given arrays into a new array.
+ * The new array contains all of the element of {@code array1} followed
+ * by all of the elements {@code array2}. When an array is returned, it is always
+ * a new array.
+ *
+ *
+ * ArrayUtils.addAll(array1, null) = cloned copy of array1
+ * ArrayUtils.addAll(null, array2) = cloned copy of array2
+ * ArrayUtils.addAll([], []) = []
+ *
+ *
+ * @param array1 the first array whose elements are added to the new array.
+ * @param array2 the second array whose elements are added to the new array.
+ * @return The new long[] array.
+ * @since 2.1
+ */
+ public static long[] addAll(long[] array1, long... array2) {
+ if (array1 == null) {
+ return clone(array2);
+ } else if (array2 == null) {
+ return clone(array1);
+ }
+ long[] joinedArray = new long[array1.length + array2.length];
+ System.arraycopy(array1, 0, joinedArray, 0, array1.length);
+ System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
+ return joinedArray;
+ }
+
+ /**
+ * Adds all the elements of the given arrays into a new array.
+ * The new array contains all of the element of {@code array1} followed
+ * by all of the elements {@code array2}. When an array is returned, it is always
+ * a new array.
+ *
+ *
+ * ArrayUtils.addAll(array1, null) = cloned copy of array1
+ * ArrayUtils.addAll(null, array2) = cloned copy of array2
+ * ArrayUtils.addAll([], []) = []
+ *
+ *
+ * @param array1 the first array whose elements are added to the new array.
+ * @param array2 the second array whose elements are added to the new array.
+ * @return The new float[] array.
+ * @since 2.1
+ */
+ public static float[] addAll(float[] array1, float... array2) {
+ if (array1 == null) {
+ return clone(array2);
+ } else if (array2 == null) {
+ return clone(array1);
+ }
+ float[] joinedArray = new float[array1.length + array2.length];
+ System.arraycopy(array1, 0, joinedArray, 0, array1.length);
+ System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
+ return joinedArray;
+ }
+
+ /**
+ * Adds all the elements of the given arrays into a new array.
+ * The new array contains all of the element of {@code array1} followed
+ * by all of the elements {@code array2}. When an array is returned, it is always
+ * a new array.
+ *
+ *
+ * ArrayUtils.addAll(array1, null) = cloned copy of array1
+ * ArrayUtils.addAll(null, array2) = cloned copy of array2
+ * ArrayUtils.addAll([], []) = []
+ *
+ *
+ * @param array1 the first array whose elements are added to the new array.
+ * @param array2 the second array whose elements are added to the new array.
+ * @return The new double[] array.
+ * @since 2.1
+ */
+ public static double[] addAll(double[] array1, double... array2) {
+ if (array1 == null) {
+ return clone(array2);
+ } else if (array2 == null) {
+ return clone(array1);
+ }
+ double[] joinedArray = new double[array1.length + array2.length];
+ System.arraycopy(array1, 0, joinedArray, 0, array1.length);
+ System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
+ return joinedArray;
+ }
+
+ /**
+ * Copies the given array and adds the given element at the end of the new array.
+ *
+ * The new array contains the same elements of the input
+ * array plus the given element in the last position. The component type of
+ * the new array is the same as that of the input array.
+ *
+ * If the input array is {@code null}, a new one element array is returned
+ * whose component type is the same as the element, unless the element itself is null,
+ * in which case the return type is Object[]
+ *
+ *
+ * ArrayUtils.add(null, null) = [null]
+ * ArrayUtils.add(null, "a") = ["a"]
+ * ArrayUtils.add(["a"], null) = ["a", null]
+ * ArrayUtils.add(["a"], "b") = ["a", "b"]
+ * ArrayUtils.add(["a", "b"], "c") = ["a", "b", "c"]
+ *
+ *
+ * @param the component type of the array
+ * @param array the array to "add" the element to, may be {@code null}
+ * @param element the object to add, may be {@code null}
+ * @return A new array containing the existing elements plus the new element
+ * The returned array type will be that of the input array (unless null),
+ * in which case it will have the same type as the element.
+ * If both are null, an IllegalArgumentException is thrown
+ * @since 2.1
+ * @throws IllegalArgumentException if both arguments are null
+ */
+ public static T[] add(T[] array, T element) {
+ Class> type;
+ if (array != null){
+ type = array.getClass();
+ } else if (element != null) {
+ type = element.getClass();
+ } else {
+ throw new IllegalArgumentException("Arguments cannot both be null");
+ }
+ @SuppressWarnings("unchecked") // type must be T
+ T[] newArray = (T[]) copyArrayGrow1(array, type);
+ newArray[newArray.length - 1] = element;
+ return newArray;
+ }
+
+ /**
+ * Copies the given array and adds the given element at the end of the new array.
+ *
+ * The new array contains the same elements of the input
+ * array plus the given element in the last position. The component type of
+ * the new array is the same as that of the input array.
+ *
+ * If the input array is {@code null}, a new one element array is returned
+ * whose component type is the same as the element.
+ *
+ *
+ * ArrayUtils.add(null, true) = [true]
+ * ArrayUtils.add([true], false) = [true, false]
+ * ArrayUtils.add([true, false], true) = [true, false, true]
+ *
+ *
+ * @param array the array to copy and add the element to, may be {@code null}
+ * @param element the object to add at the last index of the new array
+ * @return A new array containing the existing elements plus the new element
+ * @since 2.1
+ */
+ public static boolean[] add(boolean[] array, boolean element) {
+ boolean[] newArray = (boolean[])copyArrayGrow1(array, Boolean.TYPE);
+ newArray[newArray.length - 1] = element;
+ return newArray;
+ }
+
+ /**
+ * Copies the given array and adds the given element at the end of the new array.
+ *
+ * The new array contains the same elements of the input
+ * array plus the given element in the last position. The component type of
+ * the new array is the same as that of the input array.
+ *
+ * If the input array is {@code null}, a new one element array is returned
+ * whose component type is the same as the element.
+ *
+ *
+ * ArrayUtils.add(null, 0) = [0]
+ * ArrayUtils.add([1], 0) = [1, 0]
+ * ArrayUtils.add([1, 0], 1) = [1, 0, 1]
+ *
+ *
+ * @param array the array to copy and add the element to, may be {@code null}
+ * @param element the object to add at the last index of the new array
+ * @return A new array containing the existing elements plus the new element
+ * @since 2.1
+ */
+ public static byte[] add(byte[] array, byte element) {
+ byte[] newArray = (byte[])copyArrayGrow1(array, Byte.TYPE);
+ newArray[newArray.length - 1] = element;
+ return newArray;
+ }
+
+ /**
+ * Copies the given array and adds the given element at the end of the new array.
+ *
+ * The new array contains the same elements of the input
+ * array plus the given element in the last position. The component type of
+ * the new array is the same as that of the input array.
+ *
+ * If the input array is {@code null}, a new one element array is returned
+ * whose component type is the same as the element.
+ *
+ *
+ * ArrayUtils.add(null, '0') = ['0']
+ * ArrayUtils.add(['1'], '0') = ['1', '0']
+ * ArrayUtils.add(['1', '0'], '1') = ['1', '0', '1']
+ *
+ *
+ * @param array the array to copy and add the element to, may be {@code null}
+ * @param element the object to add at the last index of the new array
+ * @return A new array containing the existing elements plus the new element
+ * @since 2.1
+ */
+ public static char[] add(char[] array, char element) {
+ char[] newArray = (char[])copyArrayGrow1(array, Character.TYPE);
+ newArray[newArray.length - 1] = element;
+ return newArray;
+ }
+
+ /**
+ * Copies the given array and adds the given element at the end of the new array.
+ *
+ * The new array contains the same elements of the input
+ * array plus the given element in the last position. The component type of
+ * the new array is the same as that of the input array.
+ *
+ * If the input array is {@code null}, a new one element array is returned
+ * whose component type is the same as the element.
+ *
+ *
+ * ArrayUtils.add(null, 0) = [0]
+ * ArrayUtils.add([1], 0) = [1, 0]
+ * ArrayUtils.add([1, 0], 1) = [1, 0, 1]
+ *
+ *
+ * @param array the array to copy and add the element to, may be {@code null}
+ * @param element the object to add at the last index of the new array
+ * @return A new array containing the existing elements plus the new element
+ * @since 2.1
+ */
+ public static double[] add(double[] array, double element) {
+ double[] newArray = (double[])copyArrayGrow1(array, Double.TYPE);
+ newArray[newArray.length - 1] = element;
+ return newArray;
+ }
+
+ /**
+ * Copies the given array and adds the given element at the end of the new array.
+ *
+ * The new array contains the same elements of the input
+ * array plus the given element in the last position. The component type of
+ * the new array is the same as that of the input array.
+ *
+ * If the input array is {@code null}, a new one element array is returned
+ * whose component type is the same as the element.
+ *
+ *
+ * ArrayUtils.add(null, 0) = [0]
+ * ArrayUtils.add([1], 0) = [1, 0]
+ * ArrayUtils.add([1, 0], 1) = [1, 0, 1]
+ *
+ *
+ * @param array the array to copy and add the element to, may be {@code null}
+ * @param element the object to add at the last index of the new array
+ * @return A new array containing the existing elements plus the new element
+ * @since 2.1
+ */
+ public static float[] add(float[] array, float element) {
+ float[] newArray = (float[])copyArrayGrow1(array, Float.TYPE);
+ newArray[newArray.length - 1] = element;
+ return newArray;
+ }
+
+ /**
+ * Copies the given array and adds the given element at the end of the new array.
+ *
+ * The new array contains the same elements of the input
+ * array plus the given element in the last position. The component type of
+ * the new array is the same as that of the input array.
+ *
+ * If the input array is {@code null}, a new one element array is returned
+ * whose component type is the same as the element.
+ *
+ *
+ * ArrayUtils.add(null, 0) = [0]
+ * ArrayUtils.add([1], 0) = [1, 0]
+ * ArrayUtils.add([1, 0], 1) = [1, 0, 1]
+ *
+ *
+ * @param array the array to copy and add the element to, may be {@code null}
+ * @param element the object to add at the last index of the new array
+ * @return A new array containing the existing elements plus the new element
+ * @since 2.1
+ */
+ public static int[] add(int[] array, int element) {
+ int[] newArray = (int[])copyArrayGrow1(array, Integer.TYPE);
+ newArray[newArray.length - 1] = element;
+ return newArray;
+ }
+
+ /**
+ * Copies the given array and adds the given element at the end of the new array.
+ *
+ * The new array contains the same elements of the input
+ * array plus the given element in the last position. The component type of
+ * the new array is the same as that of the input array.
+ *
+ * If the input array is {@code null}, a new one element array is returned
+ * whose component type is the same as the element.
+ *
+ *
+ * ArrayUtils.add(null, 0) = [0]
+ * ArrayUtils.add([1], 0) = [1, 0]
+ * ArrayUtils.add([1, 0], 1) = [1, 0, 1]
+ *
+ *
+ * @param array the array to copy and add the element to, may be {@code null}
+ * @param element the object to add at the last index of the new array
+ * @return A new array containing the existing elements plus the new element
+ * @since 2.1
+ */
+ public static long[] add(long[] array, long element) {
+ long[] newArray = (long[])copyArrayGrow1(array, Long.TYPE);
+ newArray[newArray.length - 1] = element;
+ return newArray;
+ }
+
+ /**
+ * Copies the given array and adds the given element at the end of the new array.
+ *
+ * The new array contains the same elements of the input
+ * array plus the given element in the last position. The component type of
+ * the new array is the same as that of the input array.
+ *
+ * If the input array is {@code null}, a new one element array is returned
+ * whose component type is the same as the element.
+ *
+ *
+ * ArrayUtils.add(null, 0) = [0]
+ * ArrayUtils.add([1], 0) = [1, 0]
+ * ArrayUtils.add([1, 0], 1) = [1, 0, 1]
+ *
+ *
+ * @param array the array to copy and add the element to, may be {@code null}
+ * @param element the object to add at the last index of the new array
+ * @return A new array containing the existing elements plus the new element
+ * @since 2.1
+ */
+ public static short[] add(short[] array, short element) {
+ short[] newArray = (short[])copyArrayGrow1(array, Short.TYPE);
+ newArray[newArray.length - 1] = element;
+ return newArray;
+ }
+
+ /**
+ * Returns a copy of the given array of size 1 greater than the argument.
+ * The last value of the array is left to the default value.
+ *
+ * @param array The array to copy, must not be {@code null}.
+ * @param newArrayComponentType If {@code array} is {@code null}, create a
+ * size 1 array of this type.
+ * @return A new copy of the array of size 1 greater than the input.
+ */
+ private static Object copyArrayGrow1(Object array, Class> newArrayComponentType) {
+ if (array != null) {
+ int arrayLength = Array.getLength(array);
+ Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);
+ System.arraycopy(array, 0, newArray, 0, arrayLength);
+ return newArray;
+ }
+ return Array.newInstance(newArrayComponentType, 1);
+ }
+
+ /**
+ * 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 {@code null}, a new one element array is returned
+ * whose component type is the same as the element.
+ *
+ *
+ * ArrayUtils.add(null, 0, null) = [null]
+ * ArrayUtils.add(null, 0, "a") = ["a"]
+ * ArrayUtils.add(["a"], 1, null) = ["a", null]
+ * ArrayUtils.add(["a"], 1, "b") = ["a", "b"]
+ * ArrayUtils.add(["a", "b"], 3, "c") = ["a", "b", "c"]
+ *
+ *
+ * @param the component type of the array
+ * @param array the array to add the element to, may be {@code 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).
+ * @throws IllegalArgumentException if both array and element are null
+ */
+ public static T[] add(T[] array, int index, T element) {
+ Class> clss = null;
+ if (array != null) {
+ clss = array.getClass().getComponentType();
+ } else if (element != null) {
+ clss = element.getClass();
+ } else {
+ throw new IllegalArgumentException("Array and element cannot both be null");
+ }
+ @SuppressWarnings("unchecked") // the add method creates an array of type clss, which is type T
+ final T[] newArray = (T[]) add(array, index, element, clss);
+ return newArray;
+ }
+
+ /**
+ * 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 {@code null}, a new one element array is returned
+ * whose component type is the same as the element.
+ *
+ *
+ * ArrayUtils.add(null, 0, true) = [true]
+ * ArrayUtils.add([true], 0, false) = [false, true]
+ * ArrayUtils.add([false], 1, true) = [false, true]
+ * ArrayUtils.add([true, false], 1, true) = [true, true, false]
+ *
+ *
+ * @param array the array to add the element to, may be {@code 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 boolean[] add(boolean[] array, int index, boolean element) {
+ return (boolean[]) add(array, index, Boolean.valueOf(element), Boolean.TYPE);
+ }
+
+ /**
+ * 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 {@code null}, a new one element array is returned
+ * whose component type is the same as the element.
+ *
+ *
+ * ArrayUtils.add(null, 0, 'a') = ['a']
+ * ArrayUtils.add(['a'], 0, 'b') = ['b', 'a']
+ * ArrayUtils.add(['a', 'b'], 0, 'c') = ['c', 'a', 'b']
+ * ArrayUtils.add(['a', 'b'], 1, 'k') = ['a', 'k', 'b']
+ * ArrayUtils.add(['a', 'b', 'c'], 1, 't') = ['a', 't', 'b', 'c']
+ *
+ *
+ * @param array the array to add the element to, may be {@code 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 char[] add(char[] array, int index, char element) {
+ return (char[]) add(array, index, Character.valueOf(element), Character.TYPE);
+ }
+
+ /**
+ * 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 {@code null}, a new one element array is returned
+ * whose component type is the same as the element.
+ *
+ *
+ * ArrayUtils.add([1], 0, 2) = [2, 1]
+ * ArrayUtils.add([2, 6], 2, 3) = [2, 6, 3]
+ * ArrayUtils.add([2, 6], 0, 1) = [1, 2, 6]
+ * ArrayUtils.add([2, 6, 3], 2, 1) = [2, 6, 1, 3]
+ *
+ *
+ * @param array the array to add the element to, may be {@code 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 byte[] add(byte[] array, int index, byte element) {
+ return (byte[]) add(array, index, Byte.valueOf(element), Byte.TYPE);
+ }
+
+ /**
+ * 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 {@code null}, a new one element array is returned
+ * whose component type is the same as the element.
+ *
+ *
+ * ArrayUtils.add([1], 0, 2) = [2, 1]
+ * ArrayUtils.add([2, 6], 2, 10) = [2, 6, 10]
+ * ArrayUtils.add([2, 6], 0, -4) = [-4, 2, 6]
+ * ArrayUtils.add([2, 6, 3], 2, 1) = [2, 6, 1, 3]
+ *
+ *
+ * @param array the array to add the element to, may be {@code 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 short[] add(short[] array, int index, short element) {
+ return (short[]) add(array, index, Short.valueOf(element), Short.TYPE);
+ }
+
+ /**
+ * 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 {@code null}, a new one element array is returned
+ * whose component type is the same as the element.
+ *
+ *
+ * ArrayUtils.add([1], 0, 2) = [2, 1]
+ * ArrayUtils.add([2, 6], 2, 10) = [2, 6, 10]
+ * ArrayUtils.add([2, 6], 0, -4) = [-4, 2, 6]
+ * ArrayUtils.add([2, 6, 3], 2, 1) = [2, 6, 1, 3]
+ *
+ *
+ * @param array the array to add the element to, may be {@code 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 int[] add(int[] array, int index, int element) {
+ return (int[]) add(array, index, Integer.valueOf(element), Integer.TYPE);
+ }
+
+ /**
+ * 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 {@code null}, a new one element array is returned
+ * whose component type is the same as the element.
+ *
+ *
+ * ArrayUtils.add([1L], 0, 2L) = [2L, 1L]
+ * ArrayUtils.add([2L, 6L], 2, 10L) = [2L, 6L, 10L]
+ * ArrayUtils.add([2L, 6L], 0, -4L) = [-4L, 2L, 6L]
+ * ArrayUtils.add([2L, 6L, 3L], 2, 1L) = [2L, 6L, 1L, 3L]
+ *
+ *
+ * @param array the array to add the element to, may be {@code 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 long[] add(long[] array, int index, long element) {
+ return (long[]) add(array, index, Long.valueOf(element), Long.TYPE);
+ }
+
+ /**
+ * 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 {@code 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 {@code 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, Float.valueOf(element), Float.TYPE);
+ }
+
+ /**
+ * 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 {@code null}, a new one element array is returned
+ * whose component type is the same as the element.
+ *
+ *
+ * ArrayUtils.add([1.1], 0, 2.2) = [2.2, 1.1]
+ * ArrayUtils.add([2.3, 6.4], 2, 10.5) = [2.3, 6.4, 10.5]
+ * ArrayUtils.add([2.6, 6.7], 0, -4.8) = [-4.8, 2.6, 6.7]
+ * ArrayUtils.add([2.9, 6.0, 0.3], 2, 1.0) = [2.9, 6.0, 1.0, 0.3]
+ *
+ *
+ * @param array the array to add the element to, may be {@code 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 double[] add(double[] array, int index, double element) {
+ return (double[]) add(array, index, Double.valueOf(element), Double.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 {@code 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;
+ }
+
+ /**
+ * Removes the element at the specified position from the specified array.
+ * All subsequent elements are shifted to the left (subtracts one from
+ * their indices).
+ *
+ * This method returns a new array with the same elements of the input
+ * array except the 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 {@code null}, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ *
+ *
+ * ArrayUtils.remove(["a"], 0) = []
+ * ArrayUtils.remove(["a", "b"], 0) = ["b"]
+ * ArrayUtils.remove(["a", "b"], 1) = ["a"]
+ * ArrayUtils.remove(["a", "b", "c"], 1) = ["a", "c"]
+ *
+ *
+ * @param the component type of the array
+ * @param array the array to remove the element from, may not be {@code null}
+ * @param index the position of the element to be removed
+ * @return A new array containing the existing elements except the element
+ * at the specified position.
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index >= array.length), or if the array is {@code null}.
+ * @since 2.1
+ */
+ @SuppressWarnings("unchecked") // remove() always creates an array of the same type as its input
+ public static T[] remove(T[] array, int index) {
+ return (T[]) remove((Object) array, index);
+ }
+
+ /**
+ * Removes the first occurrence of the specified element from the
+ * specified array. All subsequent elements are shifted to the left
+ * (subtracts one from their indices). If the array doesn't contains
+ * such an element, no elements are removed from the array.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except the first occurrence of the specified element. The component
+ * type of the returned array is always the same as that of the input
+ * array.
+ *
+ *
+ * ArrayUtils.removeElement(null, "a") = null
+ * ArrayUtils.removeElement([], "a") = []
+ * ArrayUtils.removeElement(["a"], "b") = ["a"]
+ * ArrayUtils.removeElement(["a", "b"], "a") = ["b"]
+ * ArrayUtils.removeElement(["a", "b", "a"], "a") = ["b", "a"]
+ *
+ *
+ * @param the component type of the array
+ * @param array the array to remove the element from, may be {@code null}
+ * @param element the element to be removed
+ * @return A new array containing the existing elements except the first
+ * occurrence of the specified element.
+ * @since 2.1
+ */
+ public static T[] removeElement(T[] array, Object element) {
+ int index = indexOf(array, element);
+ if (index == INDEX_NOT_FOUND) {
+ return clone(array);
+ }
+ return remove(array, index);
+ }
+
+ /**
+ * Removes the element at the specified position from the specified array.
+ * All subsequent elements are shifted to the left (subtracts one from
+ * their indices).
+ *
+ * This method returns a new array with the same elements of the input
+ * array except the 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 {@code null}, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ *
+ *
+ * ArrayUtils.remove([true], 0) = []
+ * ArrayUtils.remove([true, false], 0) = [false]
+ * ArrayUtils.remove([true, false], 1) = [true]
+ * ArrayUtils.remove([true, true, false], 1) = [true, false]
+ *
+ *
+ * @param array the array to remove the element from, may not be {@code null}
+ * @param index the position of the element to be removed
+ * @return A new array containing the existing elements except the element
+ * at the specified position.
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index >= array.length), or if the array is {@code null}.
+ * @since 2.1
+ */
+ public static boolean[] remove(boolean[] array, int index) {
+ return (boolean[]) remove((Object) array, index);
+ }
+
+ /**
+ * Removes the first occurrence of the specified element from the
+ * specified array. All subsequent elements are shifted to the left
+ * (subtracts one from their indices). If the array doesn't contains
+ * such an element, no elements are removed from the array.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except the first occurrence of the specified element. The component
+ * type of the returned array is always the same as that of the input
+ * array.
+ *
+ *
+ * ArrayUtils.removeElement(null, true) = null
+ * ArrayUtils.removeElement([], true) = []
+ * ArrayUtils.removeElement([true], false) = [true]
+ * ArrayUtils.removeElement([true, false], false) = [true]
+ * ArrayUtils.removeElement([true, false, true], true) = [false, true]
+ *
+ *
+ * @param array the array to remove the element from, may be {@code null}
+ * @param element the element to be removed
+ * @return A new array containing the existing elements except the first
+ * occurrence of the specified element.
+ * @since 2.1
+ */
+ public static boolean[] removeElement(boolean[] array, boolean element) {
+ int index = indexOf(array, element);
+ if (index == INDEX_NOT_FOUND) {
+ return clone(array);
+ }
+ return remove(array, index);
+ }
+
+ /**
+ * Removes the element at the specified position from the specified array.
+ * All subsequent elements are shifted to the left (subtracts one from
+ * their indices).
+ *
+ * This method returns a new array with the same elements of the input
+ * array except the 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 {@code null}, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ *
+ *
+ * ArrayUtils.remove([1], 0) = []
+ * ArrayUtils.remove([1, 0], 0) = [0]
+ * ArrayUtils.remove([1, 0], 1) = [1]
+ * ArrayUtils.remove([1, 0, 1], 1) = [1, 1]
+ *
+ *
+ * @param array the array to remove the element from, may not be {@code null}
+ * @param index the position of the element to be removed
+ * @return A new array containing the existing elements except the element
+ * at the specified position.
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index >= array.length), or if the array is {@code null}.
+ * @since 2.1
+ */
+ public static byte[] remove(byte[] array, int index) {
+ return (byte[]) remove((Object) array, index);
+ }
+
+ /**
+ * Removes the first occurrence of the specified element from the
+ * specified array. All subsequent elements are shifted to the left
+ * (subtracts one from their indices). If the array doesn't contains
+ * such an element, no elements are removed from the array.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except the first occurrence of the specified element. The component
+ * type of the returned array is always the same as that of the input
+ * array.
+ *
+ *
+ * ArrayUtils.removeElement(null, 1) = null
+ * ArrayUtils.removeElement([], 1) = []
+ * ArrayUtils.removeElement([1], 0) = [1]
+ * ArrayUtils.removeElement([1, 0], 0) = [1]
+ * ArrayUtils.removeElement([1, 0, 1], 1) = [0, 1]
+ *
+ *
+ * @param array the array to remove the element from, may be {@code null}
+ * @param element the element to be removed
+ * @return A new array containing the existing elements except the first
+ * occurrence of the specified element.
+ * @since 2.1
+ */
+ public static byte[] removeElement(byte[] array, byte element) {
+ int index = indexOf(array, element);
+ if (index == INDEX_NOT_FOUND) {
+ return clone(array);
+ }
+ return remove(array, index);
+ }
+
+ /**
+ * Removes the element at the specified position from the specified array.
+ * All subsequent elements are shifted to the left (subtracts one from
+ * their indices).
+ *
+ * This method returns a new array with the same elements of the input
+ * array except the 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 {@code null}, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ *
+ *
+ * ArrayUtils.remove(['a'], 0) = []
+ * ArrayUtils.remove(['a', 'b'], 0) = ['b']
+ * ArrayUtils.remove(['a', 'b'], 1) = ['a']
+ * ArrayUtils.remove(['a', 'b', 'c'], 1) = ['a', 'c']
+ *
+ *
+ * @param array the array to remove the element from, may not be {@code null}
+ * @param index the position of the element to be removed
+ * @return A new array containing the existing elements except the element
+ * at the specified position.
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index >= array.length), or if the array is {@code null}.
+ * @since 2.1
+ */
+ public static char[] remove(char[] array, int index) {
+ return (char[]) remove((Object) array, index);
+ }
+
+ /**
+ * Removes the first occurrence of the specified element from the
+ * specified array. All subsequent elements are shifted to the left
+ * (subtracts one from their indices). If the array doesn't contains
+ * such an element, no elements are removed from the array.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except the first occurrence of the specified element. The component
+ * type of the returned array is always the same as that of the input
+ * array.
+ *
+ *
+ * ArrayUtils.removeElement(null, 'a') = null
+ * ArrayUtils.removeElement([], 'a') = []
+ * ArrayUtils.removeElement(['a'], 'b') = ['a']
+ * ArrayUtils.removeElement(['a', 'b'], 'a') = ['b']
+ * ArrayUtils.removeElement(['a', 'b', 'a'], 'a') = ['b', 'a']
+ *
+ *
+ * @param array the array to remove the element from, may be {@code null}
+ * @param element the element to be removed
+ * @return A new array containing the existing elements except the first
+ * occurrence of the specified element.
+ * @since 2.1
+ */
+ public static char[] removeElement(char[] array, char element) {
+ int index = indexOf(array, element);
+ if (index == INDEX_NOT_FOUND) {
+ return clone(array);
+ }
+ return remove(array, index);
+ }
+
+ /**
+ * Removes the element at the specified position from the specified array.
+ * All subsequent elements are shifted to the left (subtracts one from
+ * their indices).
+ *
+ * This method returns a new array with the same elements of the input
+ * array except the 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 {@code null}, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ *
+ *
+ * ArrayUtils.remove([1.1], 0) = []
+ * ArrayUtils.remove([2.5, 6.0], 0) = [6.0]
+ * ArrayUtils.remove([2.5, 6.0], 1) = [2.5]
+ * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]
+ *
+ *
+ * @param array the array to remove the element from, may not be {@code null}
+ * @param index the position of the element to be removed
+ * @return A new array containing the existing elements except the element
+ * at the specified position.
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index >= array.length), or if the array is {@code null}.
+ * @since 2.1
+ */
+ public static double[] remove(double[] array, int index) {
+ return (double[]) remove((Object) array, index);
+ }
+
+ /**
+ * Removes the first occurrence of the specified element from the
+ * specified array. All subsequent elements are shifted to the left
+ * (subtracts one from their indices). If the array doesn't contains
+ * such an element, no elements are removed from the array.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except the first occurrence of the specified element. The component
+ * type of the returned array is always the same as that of the input
+ * array.
+ *
+ *
+ * ArrayUtils.removeElement(null, 1.1) = null
+ * ArrayUtils.removeElement([], 1.1) = []
+ * ArrayUtils.removeElement([1.1], 1.2) = [1.1]
+ * ArrayUtils.removeElement([1.1, 2.3], 1.1) = [2.3]
+ * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]
+ *
+ *
+ * @param array the array to remove the element from, may be {@code null}
+ * @param element the element to be removed
+ * @return A new array containing the existing elements except the first
+ * occurrence of the specified element.
+ * @since 2.1
+ */
+ public static double[] removeElement(double[] array, double element) {
+ int index = indexOf(array, element);
+ if (index == INDEX_NOT_FOUND) {
+ return clone(array);
+ }
+ return remove(array, index);
+ }
+
+ /**
+ * Removes the element at the specified position from the specified array.
+ * All subsequent elements are shifted to the left (subtracts one from
+ * their indices).
+ *
+ * This method returns a new array with the same elements of the input
+ * array except the 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 {@code null}, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ *
+ *
+ * ArrayUtils.remove([1.1], 0) = []
+ * ArrayUtils.remove([2.5, 6.0], 0) = [6.0]
+ * ArrayUtils.remove([2.5, 6.0], 1) = [2.5]
+ * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]
+ *
+ *
+ * @param array the array to remove the element from, may not be {@code null}
+ * @param index the position of the element to be removed
+ * @return A new array containing the existing elements except the element
+ * at the specified position.
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index >= array.length), or if the array is {@code null}.
+ * @since 2.1
+ */
+ public static float[] remove(float[] array, int index) {
+ return (float[]) remove((Object) array, index);
+ }
+
+ /**
+ * Removes the first occurrence of the specified element from the
+ * specified array. All subsequent elements are shifted to the left
+ * (subtracts one from their indices). If the array doesn't contains
+ * such an element, no elements are removed from the array.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except the first occurrence of the specified element. The component
+ * type of the returned array is always the same as that of the input
+ * array.
+ *
+ *
+ * ArrayUtils.removeElement(null, 1.1) = null
+ * ArrayUtils.removeElement([], 1.1) = []
+ * ArrayUtils.removeElement([1.1], 1.2) = [1.1]
+ * ArrayUtils.removeElement([1.1, 2.3], 1.1) = [2.3]
+ * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]
+ *
+ *
+ * @param array the array to remove the element from, may be {@code null}
+ * @param element the element to be removed
+ * @return A new array containing the existing elements except the first
+ * occurrence of the specified element.
+ * @since 2.1
+ */
+ public static float[] removeElement(float[] array, float element) {
+ int index = indexOf(array, element);
+ if (index == INDEX_NOT_FOUND) {
+ return clone(array);
+ }
+ return remove(array, index);
+ }
+
+ /**
+ * Removes the element at the specified position from the specified array.
+ * All subsequent elements are shifted to the left (subtracts one from
+ * their indices).
+ *
+ * This method returns a new array with the same elements of the input
+ * array except the 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 {@code null}, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ *
+ *
+ * ArrayUtils.remove([1], 0) = []
+ * ArrayUtils.remove([2, 6], 0) = [6]
+ * ArrayUtils.remove([2, 6], 1) = [2]
+ * ArrayUtils.remove([2, 6, 3], 1) = [2, 3]
+ *
+ *
+ * @param array the array to remove the element from, may not be {@code null}
+ * @param index the position of the element to be removed
+ * @return A new array containing the existing elements except the element
+ * at the specified position.
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index >= array.length), or if the array is {@code null}.
+ * @since 2.1
+ */
+ public static int[] remove(int[] array, int index) {
+ return (int[]) remove((Object) array, index);
+ }
+
+ /**
+ * Removes the first occurrence of the specified element from the
+ * specified array. All subsequent elements are shifted to the left
+ * (subtracts one from their indices). If the array doesn't contains
+ * such an element, no elements are removed from the array.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except the first occurrence of the specified element. The component
+ * type of the returned array is always the same as that of the input
+ * array.
+ *
+ *
+ * ArrayUtils.removeElement(null, 1) = null
+ * ArrayUtils.removeElement([], 1) = []
+ * ArrayUtils.removeElement([1], 2) = [1]
+ * ArrayUtils.removeElement([1, 3], 1) = [3]
+ * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]
+ *
+ *
+ * @param array the array to remove the element from, may be {@code null}
+ * @param element the element to be removed
+ * @return A new array containing the existing elements except the first
+ * occurrence of the specified element.
+ * @since 2.1
+ */
+ public static int[] removeElement(int[] array, int element) {
+ int index = indexOf(array, element);
+ if (index == INDEX_NOT_FOUND) {
+ return clone(array);
+ }
+ return remove(array, index);
+ }
+
+ /**
+ * Removes the element at the specified position from the specified array.
+ * All subsequent elements are shifted to the left (subtracts one from
+ * their indices).
+ *
+ * This method returns a new array with the same elements of the input
+ * array except the 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 {@code null}, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ *
+ *
+ * ArrayUtils.remove([1], 0) = []
+ * ArrayUtils.remove([2, 6], 0) = [6]
+ * ArrayUtils.remove([2, 6], 1) = [2]
+ * ArrayUtils.remove([2, 6, 3], 1) = [2, 3]
+ *
+ *
+ * @param array the array to remove the element from, may not be {@code null}
+ * @param index the position of the element to be removed
+ * @return A new array containing the existing elements except the element
+ * at the specified position.
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index >= array.length), or if the array is {@code null}.
+ * @since 2.1
+ */
+ public static long[] remove(long[] array, int index) {
+ return (long[]) remove((Object) array, index);
+ }
+
+ /**
+ * Removes the first occurrence of the specified element from the
+ * specified array. All subsequent elements are shifted to the left
+ * (subtracts one from their indices). If the array doesn't contains
+ * such an element, no elements are removed from the array.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except the first occurrence of the specified element. The component
+ * type of the returned array is always the same as that of the input
+ * array.
+ *
+ *
+ * ArrayUtils.removeElement(null, 1) = null
+ * ArrayUtils.removeElement([], 1) = []
+ * ArrayUtils.removeElement([1], 2) = [1]
+ * ArrayUtils.removeElement([1, 3], 1) = [3]
+ * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]
+ *
+ *
+ * @param array the array to remove the element from, may be {@code null}
+ * @param element the element to be removed
+ * @return A new array containing the existing elements except the first
+ * occurrence of the specified element.
+ * @since 2.1
+ */
+ public static long[] removeElement(long[] array, long element) {
+ int index = indexOf(array, element);
+ if (index == INDEX_NOT_FOUND) {
+ return clone(array);
+ }
+ return remove(array, index);
+ }
+
+ /**
+ * Removes the element at the specified position from the specified array.
+ * All subsequent elements are shifted to the left (subtracts one from
+ * their indices).
+ *
+ * This method returns a new array with the same elements of the input
+ * array except the 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 {@code null}, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ *
+ *
+ * ArrayUtils.remove([1], 0) = []
+ * ArrayUtils.remove([2, 6], 0) = [6]
+ * ArrayUtils.remove([2, 6], 1) = [2]
+ * ArrayUtils.remove([2, 6, 3], 1) = [2, 3]
+ *
+ *
+ * @param array the array to remove the element from, may not be {@code null}
+ * @param index the position of the element to be removed
+ * @return A new array containing the existing elements except the element
+ * at the specified position.
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index >= array.length), or if the array is {@code null}.
+ * @since 2.1
+ */
+ public static short[] remove(short[] array, int index) {
+ return (short[]) remove((Object) array, index);
+ }
+
+ /**
+ * Removes the first occurrence of the specified element from the
+ * specified array. All subsequent elements are shifted to the left
+ * (subtracts one from their indices). If the array doesn't contains
+ * such an element, no elements are removed from the array.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except the first occurrence of the specified element. The component
+ * type of the returned array is always the same as that of the input
+ * array.
+ *
+ *
+ * ArrayUtils.removeElement(null, 1) = null
+ * ArrayUtils.removeElement([], 1) = []
+ * ArrayUtils.removeElement([1], 2) = [1]
+ * ArrayUtils.removeElement([1, 3], 1) = [3]
+ * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]
+ *
+ *
+ * @param array the array to remove the element from, may be {@code null}
+ * @param element the element to be removed
+ * @return A new array containing the existing elements except the first
+ * occurrence of the specified element.
+ * @since 2.1
+ */
+ public static short[] removeElement(short[] array, short element) {
+ int index = indexOf(array, element);
+ if (index == INDEX_NOT_FOUND) {
+ return clone(array);
+ }
+ return remove(array, index);
+ }
+
+ /**
+ * Removes the element at the specified position from the specified array.
+ * All subsequent elements are shifted to the left (subtracts one from
+ * their indices).
+ *
+ * This method returns a new array with the same elements of the input
+ * array except the 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 {@code null}, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ *
+ * @param array the array to remove the element from, may not be {@code null}
+ * @param index the position of the element to be removed
+ * @return A new array containing the existing elements except the element
+ * at the specified position.
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index >= array.length), or if the array is {@code null}.
+ * @since 2.1
+ */
+ private static Object remove(Object array, int index) {
+ int length = getLength(array);
+ if (index < 0 || index >= length) {
+ throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length);
+ }
+
+ Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);
+ System.arraycopy(array, 0, result, 0, index);
+ if (index < length - 1) {
+ System.arraycopy(array, index + 1, result, index, length - index - 1);
+ }
+
+ return result;
+ }
+
+ /**
+ * Removes the elements at the specified positions from the specified array.
+ * All remaining elements are shifted to the left.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except those at the specified positions. The component
+ * type of the returned array is always the same as that of the input
+ * array.
+ *
+ * If the input array is {@code null}, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ *
+ *
+ * ArrayUtils.removeAll(["a", "b", "c"], 0, 2) = ["b"]
+ * ArrayUtils.removeAll(["a", "b", "c"], 1, 2) = ["a"]
+ *
+ *
+ * @param the component type of the array
+ * @param array the array to remove the element from, may not be {@code null}
+ * @param indices the positions of the elements to be removed
+ * @return A new array containing the existing elements except those
+ * at the specified positions.
+ * @throws IndexOutOfBoundsException if any index is out of range
+ * (index < 0 || index >= array.length), or if the array is {@code null}.
+ * @since 3.0.1
+ */
+ @SuppressWarnings("unchecked")
+ // removeAll() always creates an array of the same type as its input
+ public static T[] removeAll(T[] array, int... indices) {
+ return (T[]) removeAll((Object) array, clone(indices));
+ }
+
+ /**
+ * Removes occurrences of specified elements, in specified quantities,
+ * from the specified array. All subsequent elements are shifted left.
+ * For any element-to-be-removed specified in greater quantities than
+ * contained in the original array, no change occurs beyond the
+ * removal of the existing matching items.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except for the earliest-encountered occurrences of the specified
+ * elements. The component type of the returned array is always the same
+ * as that of the input array.
+ *
+ *
+ * ArrayUtils.removeElements(null, "a", "b") = null
+ * ArrayUtils.removeElements([], "a", "b") = []
+ * ArrayUtils.removeElements(["a"], "b", "c") = ["a"]
+ * ArrayUtils.removeElements(["a", "b"], "a", "c") = ["b"]
+ * ArrayUtils.removeElements(["a", "b", "a"], "a") = ["b", "a"]
+ * ArrayUtils.removeElements(["a", "b", "a"], "a", "a") = ["b"]
+ *
+ *
+ * @param the component type of the array
+ * @param array the array to remove the element from, may be {@code null}
+ * @param values the elements to be removed
+ * @return A new array containing the existing elements except the
+ * earliest-encountered occurrences of the specified elements.
+ * @since 3.0.1
+ */
+ public static T[] removeElements(T[] array, T... values) {
+ if (isEmpty(array) || isEmpty(values)) {
+ return clone(array);
+ }
+ HashMap occurrences = new HashMap(values.length);
+ for (T v : values) {
+ MutableInt count = occurrences.get(v);
+ if (count == null) {
+ occurrences.put(v, new MutableInt(1));
+ } else {
+ count.increment();
+ }
+ }
+ HashSet toRemove = new HashSet();
+ for (Map.Entry e : occurrences.entrySet()) {
+ T v = e.getKey();
+ int found = 0;
+ for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) {
+ found = indexOf(array, v, found);
+ if (found < 0) {
+ break;
+ }
+ toRemove.add(found++);
+ }
+ }
+ return removeAll(array, extractIndices(toRemove));
+ }
+
+ /**
+ * Removes the elements at the specified positions from the specified array.
+ * All remaining elements are shifted to the left.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except those at the specified positions. The component
+ * type of the returned array is always the same as that of the input
+ * array.
+ *
+ * If the input array is {@code null}, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ *
+ *
+ * ArrayUtils.removeAll([1], 0) = []
+ * ArrayUtils.removeAll([2, 6], 0) = [6]
+ * ArrayUtils.removeAll([2, 6], 0, 1) = []
+ * ArrayUtils.removeAll([2, 6, 3], 1, 2) = [2]
+ * ArrayUtils.removeAll([2, 6, 3], 0, 2) = [6]
+ * ArrayUtils.removeAll([2, 6, 3], 0, 1, 2) = []
+ *
+ *
+ * @param array the array to remove the element from, may not be {@code null}
+ * @param indices the positions of the elements to be removed
+ * @return A new array containing the existing elements except those
+ * at the specified positions.
+ * @throws IndexOutOfBoundsException if any index is out of range
+ * (index < 0 || index >= array.length), or if the array is {@code null}.
+ * @since 3.0.1
+ */
+ public static byte[] removeAll(byte[] array, int... indices) {
+ return (byte[]) removeAll((Object) array, clone(indices));
+ }
+
+ /**
+ * Removes occurrences of specified elements, in specified quantities,
+ * from the specified array. All subsequent elements are shifted left.
+ * For any element-to-be-removed specified in greater quantities than
+ * contained in the original array, no change occurs beyond the
+ * removal of the existing matching items.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except for the earliest-encountered occurrences of the specified
+ * elements. The component type of the returned array is always the same
+ * as that of the input array.
+ *
+ *
+ * ArrayUtils.removeElements(null, 1, 2) = null
+ * ArrayUtils.removeElements([], 1, 2) = []
+ * ArrayUtils.removeElements([1], 2, 3) = [1]
+ * ArrayUtils.removeElements([1, 3], 1, 2) = [3]
+ * ArrayUtils.removeElements([1, 3, 1], 1) = [3, 1]
+ * ArrayUtils.removeElements([1, 3, 1], 1, 1) = [3]
+ *
+ *
+ * @param array the array to remove the element from, may be {@code null}
+ * @param values the elements to be removed
+ * @return A new array containing the existing elements except the
+ * earliest-encountered occurrences of the specified elements.
+ * @since 3.0.1
+ */
+ public static byte[] removeElements(byte[] array, byte... values) {
+ if (isEmpty(array) || isEmpty(values)) {
+ return clone(array);
+ }
+ HashMap occurrences = new HashMap(values.length);
+ for (byte v : values) {
+ Byte boxed = Byte.valueOf(v);
+ MutableInt count = occurrences.get(boxed);
+ if (count == null) {
+ occurrences.put(boxed, new MutableInt(1));
+ } else {
+ count.increment();
+ }
+ }
+ HashSet toRemove = new HashSet();
+ for (Map.Entry e : occurrences.entrySet()) {
+ Byte v = e.getKey();
+ int found = 0;
+ for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) {
+ found = indexOf(array, v.byteValue(), found);
+ if (found < 0) {
+ break;
+ }
+ toRemove.add(found++);
+ }
+ }
+ return removeAll(array, extractIndices(toRemove));
+ }
+
+ /**
+ * Removes the elements at the specified positions from the specified array.
+ * All remaining elements are shifted to the left.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except those at the specified positions. The component
+ * type of the returned array is always the same as that of the input
+ * array.
+ *
+ * If the input array is {@code null}, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ *
+ *
+ * ArrayUtils.removeAll([1], 0) = []
+ * ArrayUtils.removeAll([2, 6], 0) = [6]
+ * ArrayUtils.removeAll([2, 6], 0, 1) = []
+ * ArrayUtils.removeAll([2, 6, 3], 1, 2) = [2]
+ * ArrayUtils.removeAll([2, 6, 3], 0, 2) = [6]
+ * ArrayUtils.removeAll([2, 6, 3], 0, 1, 2) = []
+ *
+ *
+ * @param array the array to remove the element from, may not be {@code null}
+ * @param indices the positions of the elements to be removed
+ * @return A new array containing the existing elements except those
+ * at the specified positions.
+ * @throws IndexOutOfBoundsException if any index is out of range
+ * (index < 0 || index >= array.length), or if the array is {@code null}.
+ * @since 3.0.1
+ */
+ public static short[] removeAll(short[] array, int... indices) {
+ return (short[]) removeAll((Object) array, clone(indices));
+ }
+
+ /**
+ * Removes occurrences of specified elements, in specified quantities,
+ * from the specified array. All subsequent elements are shifted left.
+ * For any element-to-be-removed specified in greater quantities than
+ * contained in the original array, no change occurs beyond the
+ * removal of the existing matching items.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except for the earliest-encountered occurrences of the specified
+ * elements. The component type of the returned array is always the same
+ * as that of the input array.
+ *
+ *
+ * ArrayUtils.removeElements(null, 1, 2) = null
+ * ArrayUtils.removeElements([], 1, 2) = []
+ * ArrayUtils.removeElements([1], 2, 3) = [1]
+ * ArrayUtils.removeElements([1, 3], 1, 2) = [3]
+ * ArrayUtils.removeElements([1, 3, 1], 1) = [3, 1]
+ * ArrayUtils.removeElements([1, 3, 1], 1, 1) = [3]
+ *
+ *
+ * @param array the array to remove the element from, may be {@code null}
+ * @param values the elements to be removed
+ * @return A new array containing the existing elements except the
+ * earliest-encountered occurrences of the specified elements.
+ * @since 3.0.1
+ */
+ public static short[] removeElements(short[] array, short... values) {
+ if (isEmpty(array) || isEmpty(values)) {
+ return clone(array);
+ }
+ HashMap occurrences = new HashMap(values.length);
+ for (short v : values) {
+ Short boxed = Short.valueOf(v);
+ MutableInt count = occurrences.get(boxed);
+ if (count == null) {
+ occurrences.put(boxed, new MutableInt(1));
+ } else {
+ count.increment();
+ }
+ }
+ HashSet toRemove = new HashSet();
+ for (Map.Entry e : occurrences.entrySet()) {
+ Short v = e.getKey();
+ int found = 0;
+ for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) {
+ found = indexOf(array, v.shortValue(), found);
+ if (found < 0) {
+ break;
+ }
+ toRemove.add(found++);
+ }
+ }
+ return removeAll(array, extractIndices(toRemove));
+ }
+
+ /**
+ * Removes the elements at the specified positions from the specified array.
+ * All remaining elements are shifted to the left.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except those at the specified positions. The component
+ * type of the returned array is always the same as that of the input
+ * array.
+ *
+ * If the input array is {@code null}, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ *
+ *
+ * ArrayUtils.removeAll([1], 0) = []
+ * ArrayUtils.removeAll([2, 6], 0) = [6]
+ * ArrayUtils.removeAll([2, 6], 0, 1) = []
+ * ArrayUtils.removeAll([2, 6, 3], 1, 2) = [2]
+ * ArrayUtils.removeAll([2, 6, 3], 0, 2) = [6]
+ * ArrayUtils.removeAll([2, 6, 3], 0, 1, 2) = []
+ *
+ *
+ * @param array the array to remove the element from, may not be {@code null}
+ * @param indices the positions of the elements to be removed
+ * @return A new array containing the existing elements except those
+ * at the specified positions.
+ * @throws IndexOutOfBoundsException if any index is out of range
+ * (index < 0 || index >= array.length), or if the array is {@code null}.
+ * @since 3.0.1
+ */
+ public static int[] removeAll(int[] array, int... indices) {
+ return (int[]) removeAll((Object) array, clone(indices));
+ }
+
+ /**
+ * Removes occurrences of specified elements, in specified quantities,
+ * from the specified array. All subsequent elements are shifted left.
+ * For any element-to-be-removed specified in greater quantities than
+ * contained in the original array, no change occurs beyond the
+ * removal of the existing matching items.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except for the earliest-encountered occurrences of the specified
+ * elements. The component type of the returned array is always the same
+ * as that of the input array.
+ *
+ *
+ * ArrayUtils.removeElements(null, 1, 2) = null
+ * ArrayUtils.removeElements([], 1, 2) = []
+ * ArrayUtils.removeElements([1], 2, 3) = [1]
+ * ArrayUtils.removeElements([1, 3], 1, 2) = [3]
+ * ArrayUtils.removeElements([1, 3, 1], 1) = [3, 1]
+ * ArrayUtils.removeElements([1, 3, 1], 1, 1) = [3]
+ *
+ *
+ * @param array the array to remove the element from, may be {@code null}
+ * @param values the elements to be removed
+ * @return A new array containing the existing elements except the
+ * earliest-encountered occurrences of the specified elements.
+ * @since 3.0.1
+ */
+ public static int[] removeElements(int[] array, int... values) {
+ if (isEmpty(array) || isEmpty(values)) {
+ return clone(array);
+ }
+ HashMap occurrences = new HashMap(values.length);
+ for (int v : values) {
+ Integer boxed = Integer.valueOf(v);
+ MutableInt count = occurrences.get(boxed);
+ if (count == null) {
+ occurrences.put(boxed, new MutableInt(1));
+ } else {
+ count.increment();
+ }
+ }
+ HashSet toRemove = new HashSet();
+ for (Map.Entry e : occurrences.entrySet()) {
+ Integer v = e.getKey();
+ int found = 0;
+ for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) {
+ found = indexOf(array, v.intValue(), found);
+ if (found < 0) {
+ break;
+ }
+ toRemove.add(found++);
+ }
+ }
+ return removeAll(array, extractIndices(toRemove));
+ }
+
+ /**
+ * Removes the elements at the specified positions from the specified array.
+ * All remaining elements are shifted to the left.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except those at the specified positions. The component
+ * type of the returned array is always the same as that of the input
+ * array.
+ *
+ * If the input array is {@code null}, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ *
+ *
+ * ArrayUtils.removeAll([1], 0) = []
+ * ArrayUtils.removeAll([2, 6], 0) = [6]
+ * ArrayUtils.removeAll([2, 6], 0, 1) = []
+ * ArrayUtils.removeAll([2, 6, 3], 1, 2) = [2]
+ * ArrayUtils.removeAll([2, 6, 3], 0, 2) = [6]
+ * ArrayUtils.removeAll([2, 6, 3], 0, 1, 2) = []
+ *
+ *
+ * @param array the array to remove the element from, may not be {@code null}
+ * @param indices the positions of the elements to be removed
+ * @return A new array containing the existing elements except those
+ * at the specified positions.
+ * @throws IndexOutOfBoundsException if any index is out of range
+ * (index < 0 || index >= array.length), or if the array is {@code null}.
+ * @since 3.0.1
+ */
+ public static char[] removeAll(char[] array, int... indices) {
+ return (char[]) removeAll((Object) array, clone(indices));
+ }
+
+ /**
+ * Removes occurrences of specified elements, in specified quantities,
+ * from the specified array. All subsequent elements are shifted left.
+ * For any element-to-be-removed specified in greater quantities than
+ * contained in the original array, no change occurs beyond the
+ * removal of the existing matching items.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except for the earliest-encountered occurrences of the specified
+ * elements. The component type of the returned array is always the same
+ * as that of the input array.
+ *
+ *
+ * ArrayUtils.removeElements(null, 1, 2) = null
+ * ArrayUtils.removeElements([], 1, 2) = []
+ * ArrayUtils.removeElements([1], 2, 3) = [1]
+ * ArrayUtils.removeElements([1, 3], 1, 2) = [3]
+ * ArrayUtils.removeElements([1, 3, 1], 1) = [3, 1]
+ * ArrayUtils.removeElements([1, 3, 1], 1, 1) = [3]
+ *
+ *
+ * @param array the array to remove the element from, may be {@code null}
+ * @param values the elements to be removed
+ * @return A new array containing the existing elements except the
+ * earliest-encountered occurrences of the specified elements.
+ * @since 3.0.1
+ */
+ public static char[] removeElements(char[] array, char... values) {
+ if (isEmpty(array) || isEmpty(values)) {
+ return clone(array);
+ }
+ HashMap occurrences = new HashMap(values.length);
+ for (char v : values) {
+ Character boxed = Character.valueOf(v);
+ MutableInt count = occurrences.get(boxed);
+ if (count == null) {
+ occurrences.put(boxed, new MutableInt(1));
+ } else {
+ count.increment();
+ }
+ }
+ HashSet toRemove = new HashSet();
+ for (Map.Entry e : occurrences.entrySet()) {
+ Character v = e.getKey();
+ int found = 0;
+ for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) {
+ found = indexOf(array, v.charValue(), found);
+ if (found < 0) {
+ break;
+ }
+ toRemove.add(found++);
+ }
+ }
+ return removeAll(array, extractIndices(toRemove));
+ }
+
+ /**
+ * Removes the elements at the specified positions from the specified array.
+ * All remaining elements are shifted to the left.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except those at the specified positions. The component
+ * type of the returned array is always the same as that of the input
+ * array.
+ *
+ * If the input array is {@code null}, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ *
+ *
+ * ArrayUtils.removeAll([1], 0) = []
+ * ArrayUtils.removeAll([2, 6], 0) = [6]
+ * ArrayUtils.removeAll([2, 6], 0, 1) = []
+ * ArrayUtils.removeAll([2, 6, 3], 1, 2) = [2]
+ * ArrayUtils.removeAll([2, 6, 3], 0, 2) = [6]
+ * ArrayUtils.removeAll([2, 6, 3], 0, 1, 2) = []
+ *
+ *
+ * @param array the array to remove the element from, may not be {@code null}
+ * @param indices the positions of the elements to be removed
+ * @return A new array containing the existing elements except those
+ * at the specified positions.
+ * @throws IndexOutOfBoundsException if any index is out of range
+ * (index < 0 || index >= array.length), or if the array is {@code null}.
+ * @since 3.0.1
+ */
+ public static long[] removeAll(long[] array, int... indices) {
+ return (long[]) removeAll((Object) array, clone(indices));
+ }
+
+ /**
+ * Removes occurrences of specified elements, in specified quantities,
+ * from the specified array. All subsequent elements are shifted left.
+ * For any element-to-be-removed specified in greater quantities than
+ * contained in the original array, no change occurs beyond the
+ * removal of the existing matching items.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except for the earliest-encountered occurrences of the specified
+ * elements. The component type of the returned array is always the same
+ * as that of the input array.
+ *
+ *
+ * ArrayUtils.removeElements(null, 1, 2) = null
+ * ArrayUtils.removeElements([], 1, 2) = []
+ * ArrayUtils.removeElements([1], 2, 3) = [1]
+ * ArrayUtils.removeElements([1, 3], 1, 2) = [3]
+ * ArrayUtils.removeElements([1, 3, 1], 1) = [3, 1]
+ * ArrayUtils.removeElements([1, 3, 1], 1, 1) = [3]
+ *
+ *
+ * @param array the array to remove the element from, may be {@code null}
+ * @param values the elements to be removed
+ * @return A new array containing the existing elements except the
+ * earliest-encountered occurrences of the specified elements.
+ * @since 3.0.1
+ */
+ public static long[] removeElements(long[] array, long... values) {
+ if (isEmpty(array) || isEmpty(values)) {
+ return clone(array);
+ }
+ HashMap occurrences = new HashMap(values.length);
+ for (long v : values) {
+ Long boxed = Long.valueOf(v);
+ MutableInt count = occurrences.get(boxed);
+ if (count == null) {
+ occurrences.put(boxed, new MutableInt(1));
+ } else {
+ count.increment();
+ }
+ }
+ HashSet toRemove = new HashSet();
+ for (Map.Entry e : occurrences.entrySet()) {
+ Long v = e.getKey();
+ int found = 0;
+ for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) {
+ found = indexOf(array, v.longValue(), found);
+ if (found < 0) {
+ break;
+ }
+ toRemove.add(found++);
+ }
+ }
+ return removeAll(array, extractIndices(toRemove));
+ }
+
+ /**
+ * Removes the elements at the specified positions from the specified array.
+ * All remaining elements are shifted to the left.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except those at the specified positions. The component
+ * type of the returned array is always the same as that of the input
+ * array.
+ *
+ * If the input array is {@code null}, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ *
+ *
+ * ArrayUtils.removeAll([1], 0) = []
+ * ArrayUtils.removeAll([2, 6], 0) = [6]
+ * ArrayUtils.removeAll([2, 6], 0, 1) = []
+ * ArrayUtils.removeAll([2, 6, 3], 1, 2) = [2]
+ * ArrayUtils.removeAll([2, 6, 3], 0, 2) = [6]
+ * ArrayUtils.removeAll([2, 6, 3], 0, 1, 2) = []
+ *
+ *
+ * @param array the array to remove the element from, may not be {@code null}
+ * @param indices the positions of the elements to be removed
+ * @return A new array containing the existing elements except those
+ * at the specified positions.
+ * @throws IndexOutOfBoundsException if any index is out of range
+ * (index < 0 || index >= array.length), or if the array is {@code null}.
+ * @since 3.0.1
+ */
+ public static float[] removeAll(float[] array, int... indices) {
+ return (float[]) removeAll((Object) array, clone(indices));
+ }
+
+ /**
+ * Removes occurrences of specified elements, in specified quantities,
+ * from the specified array. All subsequent elements are shifted left.
+ * For any element-to-be-removed specified in greater quantities than
+ * contained in the original array, no change occurs beyond the
+ * removal of the existing matching items.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except for the earliest-encountered occurrences of the specified
+ * elements. The component type of the returned array is always the same
+ * as that of the input array.
+ *
+ *
+ * ArrayUtils.removeElements(null, 1, 2) = null
+ * ArrayUtils.removeElements([], 1, 2) = []
+ * ArrayUtils.removeElements([1], 2, 3) = [1]
+ * ArrayUtils.removeElements([1, 3], 1, 2) = [3]
+ * ArrayUtils.removeElements([1, 3, 1], 1) = [3, 1]
+ * ArrayUtils.removeElements([1, 3, 1], 1, 1) = [3]
+ *
+ *
+ * @param array the array to remove the element from, may be {@code null}
+ * @param values the elements to be removed
+ * @return A new array containing the existing elements except the
+ * earliest-encountered occurrences of the specified elements.
+ * @since 3.0.1
+ */
+ public static float[] removeElements(float[] array, float... values) {
+ if (isEmpty(array) || isEmpty(values)) {
+ return clone(array);
+ }
+ HashMap occurrences = new HashMap(values.length);
+ for (float v : values) {
+ Float boxed = Float.valueOf(v);
+ MutableInt count = occurrences.get(boxed);
+ if (count == null) {
+ occurrences.put(boxed, new MutableInt(1));
+ } else {
+ count.increment();
+ }
+ }
+ HashSet toRemove = new HashSet();
+ for (Map.Entry e : occurrences.entrySet()) {
+ Float v = e.getKey();
+ int found = 0;
+ for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) {
+ found = indexOf(array, v.floatValue(), found);
+ if (found < 0) {
+ break;
+ }
+ toRemove.add(found++);
+ }
+ }
+ return removeAll(array, extractIndices(toRemove));
+ }
+
+ /**
+ * Removes the elements at the specified positions from the specified array.
+ * All remaining elements are shifted to the left.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except those at the specified positions. The component
+ * type of the returned array is always the same as that of the input
+ * array.
+ *
+ * If the input array is {@code null}, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ *
+ *
+ * ArrayUtils.removeAll([1], 0) = []
+ * ArrayUtils.removeAll([2, 6], 0) = [6]
+ * ArrayUtils.removeAll([2, 6], 0, 1) = []
+ * ArrayUtils.removeAll([2, 6, 3], 1, 2) = [2]
+ * ArrayUtils.removeAll([2, 6, 3], 0, 2) = [6]
+ * ArrayUtils.removeAll([2, 6, 3], 0, 1, 2) = []
+ *
+ *
+ * @param array the array to remove the element from, may not be {@code null}
+ * @param indices the positions of the elements to be removed
+ * @return A new array containing the existing elements except those
+ * at the specified positions.
+ * @throws IndexOutOfBoundsException if any index is out of range
+ * (index < 0 || index >= array.length), or if the array is {@code null}.
+ * @since 3.0.1
+ */
+ public static double[] removeAll(double[] array, int... indices) {
+ return (double[]) removeAll((Object) array, clone(indices));
+ }
+
+ /**
+ * Removes occurrences of specified elements, in specified quantities,
+ * from the specified array. All subsequent elements are shifted left.
+ * For any element-to-be-removed specified in greater quantities than
+ * contained in the original array, no change occurs beyond the
+ * removal of the existing matching items.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except for the earliest-encountered occurrences of the specified
+ * elements. The component type of the returned array is always the same
+ * as that of the input array.
+ *
+ *
+ * ArrayUtils.removeElements(null, 1, 2) = null
+ * ArrayUtils.removeElements([], 1, 2) = []
+ * ArrayUtils.removeElements([1], 2, 3) = [1]
+ * ArrayUtils.removeElements([1, 3], 1, 2) = [3]
+ * ArrayUtils.removeElements([1, 3, 1], 1) = [3, 1]
+ * ArrayUtils.removeElements([1, 3, 1], 1, 1) = [3]
+ *
+ *
+ * @param array the array to remove the element from, may be {@code null}
+ * @param values the elements to be removed
+ * @return A new array containing the existing elements except the
+ * earliest-encountered occurrences of the specified elements.
+ * @since 3.0.1
+ */
+ public static double[] removeElements(double[] array, double... values) {
+ if (isEmpty(array) || isEmpty(values)) {
+ return clone(array);
+ }
+ HashMap occurrences = new HashMap(values.length);
+ for (double v : values) {
+ Double boxed = Double.valueOf(v);
+ MutableInt count = occurrences.get(boxed);
+ if (count == null) {
+ occurrences.put(boxed, new MutableInt(1));
+ } else {
+ count.increment();
+ }
+ }
+ HashSet toRemove = new HashSet();
+ for (Map.Entry e : occurrences.entrySet()) {
+ Double v = e.getKey();
+ int found = 0;
+ for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) {
+ found = indexOf(array, v.doubleValue(), found);
+ if (found < 0) {
+ break;
+ }
+ toRemove.add(found++);
+ }
+ }
+ return removeAll(array, extractIndices(toRemove));
+ }
+
+ /**
+ * Removes the elements at the specified positions from the specified array.
+ * All remaining elements are shifted to the left.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except those at the specified positions. The component
+ * type of the returned array is always the same as that of the input
+ * array.
+ *
+ * If the input array is {@code null}, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ *
+ *
+ * ArrayUtils.removeAll([true, false, true], 0, 2) = [false]
+ * ArrayUtils.removeAll([true, false, true], 1, 2) = [true]
+ *
+ *
+ * @param array the array to remove the element from, may not be {@code null}
+ * @param indices the positions of the elements to be removed
+ * @return A new array containing the existing elements except those
+ * at the specified positions.
+ * @throws IndexOutOfBoundsException if any index is out of range
+ * (index < 0 || index >= array.length), or if the array is {@code null}.
+ * @since 3.0.1
+ */
+ public static boolean[] removeAll(boolean[] array, int... indices) {
+ return (boolean[]) removeAll((Object) array, clone(indices));
+ }
+
+ /**
+ * Removes occurrences of specified elements, in specified quantities,
+ * from the specified array. All subsequent elements are shifted left.
+ * For any element-to-be-removed specified in greater quantities than
+ * contained in the original array, no change occurs beyond the
+ * removal of the existing matching items.
+ *
+ * This method returns a new array with the same elements of the input
+ * array except for the earliest-encountered occurrences of the specified
+ * elements. The component type of the returned array is always the same
+ * as that of the input array.
+ *
+ *
+ * ArrayUtils.removeElements(null, true, false) = null
+ * ArrayUtils.removeElements([], true, false) = []
+ * ArrayUtils.removeElements([true], false, false) = [true]
+ * ArrayUtils.removeElements([true, false], true, true) = [false]
+ * ArrayUtils.removeElements([true, false, true], true) = [false, true]
+ * ArrayUtils.removeElements([true, false, true], true, true) = [false]
+ *
+ *
+ * @param array the array to remove the element from, may be {@code null}
+ * @param values the elements to be removed
+ * @return A new array containing the existing elements except the
+ * earliest-encountered occurrences of the specified elements.
+ * @since 3.0.1
+ */
+ public static boolean[] removeElements(boolean[] array, boolean... values) {
+ if (isEmpty(array) || isEmpty(values)) {
+ return clone(array);
+ }
+ HashMap occurrences = new HashMap(values.length);
+ for (boolean v : values) {
+ Boolean boxed = Boolean.valueOf(v);
+ MutableInt count = occurrences.get(boxed);
+ if (count == null) {
+ occurrences.put(boxed, new MutableInt(1));
+ } else {
+ count.increment();
+ }
+ }
+ HashSet toRemove = new HashSet();
+ for (Map.Entry e : occurrences.entrySet()) {
+ Boolean v = e.getKey();
+ int found = 0;
+ for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) {
+ found = indexOf(array, v.booleanValue(), found);
+ if (found < 0) {
+ break;
+ }
+ toRemove.add(found++);
+ }
+ }
+ return removeAll(array, extractIndices(toRemove));
+ }
+
+ /**
+ * Removes multiple array elements specified by index.
+ * @param array source
+ * @param indices to remove, WILL BE SORTED--so only clones of user-owned arrays!
+ * @return new array of same type minus elements specified by unique values of {@code indices}
+ * @since 3.0.1
+ */
+ private static Object removeAll(Object array, int... indices) {
+ int length = getLength(array);
+ int diff = 0;
+
+ if (isNotEmpty(indices)) {
+ Arrays.sort(indices);
+
+ int i = indices.length;
+ int prevIndex = length;
+ while (--i >= 0) {
+ int index = indices[i];
+ if (index < 0 || index >= length) {
+ throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length);
+ }
+ if (index >= prevIndex) {
+ continue;
+ }
+ diff++;
+ prevIndex = index;
+ }
+ }
+ Object result = Array.newInstance(array.getClass().getComponentType(), length - diff);
+ if (diff < length) {
+ int end = length;
+ int dest = length - diff;
+ for (int i = indices.length - 1; i >= 0; i--) {
+ int index = indices[i];
+ if (end - index > 1) {
+ int cp = end - index - 1;
+ dest -= cp;
+ System.arraycopy(array, index + 1, result, dest, cp);
+ }
+ end = index;
+ }
+ if (end > 0) {
+ System.arraycopy(array, 0, result, 0, end);
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Extract a set of Integer indices into an int[].
+ * @param coll {@code HashSet} of {@code Integer}
+ * @return int[]
+ * @since 3.0.1
+ */
+ private static int[] extractIndices(HashSet coll) {
+ int[] result = new int[coll.size()];
+ int i = 0;
+ for (Integer index : coll) {
+ result[i++] = index.intValue();
+ }
+ return result;
+ }
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/ArrayUtilsAddTest.java b/ApacheCommonsLang/org/apache/commons/lang3/ArrayUtilsAddTest.java
new file mode 100644
index 0000000..26bebb8
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/ArrayUtilsAddTest.java
@@ -0,0 +1,610 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+package org.apache.commons.lang3;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.util.Arrays;
+
+import org.junit.Test;
+
+/**
+ * Tests ArrayUtils add methods.
+ *
+ * @version $Id: ArrayUtilsAddTest.java 1199894 2011-11-09 17:53:59Z ggregory $
+ */
+public class ArrayUtilsAddTest {
+
+ @Test
+ public void testJira567(){
+ Number[] n;
+ // Valid array construction
+ n = ArrayUtils.addAll(new Number[]{Integer.valueOf(1)}, new Long[]{Long.valueOf(2)});
+ assertEquals(2,n.length);
+ assertEquals(Number.class,n.getClass().getComponentType());
+ try {
+ // Invalid - can't store Long in Integer array
+ n = ArrayUtils.addAll(new Integer[]{Integer.valueOf(1)}, new Long[]{Long.valueOf(2)});
+ fail("Should have generated IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ @Test
+ public void testAddObjectArrayBoolean() {
+ boolean[] newArray;
+ newArray = ArrayUtils.add((boolean[])null, false);
+ assertTrue(Arrays.equals(new boolean[]{false}, newArray));
+ assertEquals(Boolean.TYPE, newArray.getClass().getComponentType());
+ newArray = ArrayUtils.add((boolean[])null, true);
+ assertTrue(Arrays.equals(new boolean[]{true}, newArray));
+ assertEquals(Boolean.TYPE, newArray.getClass().getComponentType());
+ boolean[] array1 = new boolean[]{true, false, true};
+ newArray = ArrayUtils.add(array1, false);
+ assertTrue(Arrays.equals(new boolean[]{true, false, true, false}, newArray));
+ assertEquals(Boolean.TYPE, newArray.getClass().getComponentType());
+ }
+
+ @Test
+ public void testAddObjectArrayByte() {
+ byte[] newArray;
+ newArray = ArrayUtils.add((byte[])null, (byte)0);
+ assertTrue(Arrays.equals(new byte[]{0}, newArray));
+ assertEquals(Byte.TYPE, newArray.getClass().getComponentType());
+ newArray = ArrayUtils.add((byte[])null, (byte)1);
+ assertTrue(Arrays.equals(new byte[]{1}, newArray));
+ assertEquals(Byte.TYPE, newArray.getClass().getComponentType());
+ byte[] array1 = new byte[]{1, 2, 3};
+ newArray = ArrayUtils.add(array1, (byte)0);
+ assertTrue(Arrays.equals(new byte[]{1, 2, 3, 0}, newArray));
+ assertEquals(Byte.TYPE, newArray.getClass().getComponentType());
+ newArray = ArrayUtils.add(array1, (byte)4);
+ assertTrue(Arrays.equals(new byte[]{1, 2, 3, 4}, newArray));
+ assertEquals(Byte.TYPE, newArray.getClass().getComponentType());
+ }
+
+ @Test
+ public void testAddObjectArrayChar() {
+ char[] newArray;
+ newArray = ArrayUtils.add((char[])null, (char)0);
+ assertTrue(Arrays.equals(new char[]{0}, newArray));
+ assertEquals(Character.TYPE, newArray.getClass().getComponentType());
+ newArray = ArrayUtils.add((char[])null, (char)1);
+ assertTrue(Arrays.equals(new char[]{1}, newArray));
+ assertEquals(Character.TYPE, newArray.getClass().getComponentType());
+ char[] array1 = new char[]{1, 2, 3};
+ newArray = ArrayUtils.add(array1, (char)0);
+ assertTrue(Arrays.equals(new char[]{1, 2, 3, 0}, newArray));
+ assertEquals(Character.TYPE, newArray.getClass().getComponentType());
+ newArray = ArrayUtils.add(array1, (char)4);
+ assertTrue(Arrays.equals(new char[]{1, 2, 3, 4}, newArray));
+ assertEquals(Character.TYPE, newArray.getClass().getComponentType());
+ }
+
+ @Test
+ public void testAddObjectArrayDouble() {
+ double[] newArray;
+ newArray = ArrayUtils.add((double[])null, 0);
+ assertTrue(Arrays.equals(new double[]{0}, newArray));
+ assertEquals(Double.TYPE, newArray.getClass().getComponentType());
+ newArray = ArrayUtils.add((double[])null, 1);
+ assertTrue(Arrays.equals(new double[]{1}, newArray));
+ assertEquals(Double.TYPE, newArray.getClass().getComponentType());
+ double[] array1 = new double[]{1, 2, 3};
+ newArray = ArrayUtils.add(array1, 0);
+ assertTrue(Arrays.equals(new double[]{1, 2, 3, 0}, newArray));
+ assertEquals(Double.TYPE, newArray.getClass().getComponentType());
+ newArray = ArrayUtils.add(array1, 4);
+ assertTrue(Arrays.equals(new double[]{1, 2, 3, 4}, newArray));
+ assertEquals(Double.TYPE, newArray.getClass().getComponentType());
+ }
+
+ @Test
+ public void testAddObjectArrayFloat() {
+ float[] newArray;
+ newArray = ArrayUtils.add((float[])null, 0);
+ assertTrue(Arrays.equals(new float[]{0}, newArray));
+ assertEquals(Float.TYPE, newArray.getClass().getComponentType());
+ newArray = ArrayUtils.add((float[])null, 1);
+ assertTrue(Arrays.equals(new float[]{1}, newArray));
+ assertEquals(Float.TYPE, newArray.getClass().getComponentType());
+ float[] array1 = new float[]{1, 2, 3};
+ newArray = ArrayUtils.add(array1, 0);
+ assertTrue(Arrays.equals(new float[]{1, 2, 3, 0}, newArray));
+ assertEquals(Float.TYPE, newArray.getClass().getComponentType());
+ newArray = ArrayUtils.add(array1, 4);
+ assertTrue(Arrays.equals(new float[]{1, 2, 3, 4}, newArray));
+ assertEquals(Float.TYPE, newArray.getClass().getComponentType());
+ }
+
+ @Test
+ public void testAddObjectArrayInt() {
+ int[] newArray;
+ newArray = ArrayUtils.add((int[])null, 0);
+ assertTrue(Arrays.equals(new int[]{0}, newArray));
+ assertEquals(Integer.TYPE, newArray.getClass().getComponentType());
+ newArray = ArrayUtils.add((int[])null, 1);
+ assertTrue(Arrays.equals(new int[]{1}, newArray));
+ assertEquals(Integer.TYPE, newArray.getClass().getComponentType());
+ int[] array1 = new int[]{1, 2, 3};
+ newArray = ArrayUtils.add(array1, 0);
+ assertTrue(Arrays.equals(new int[]{1, 2, 3, 0}, newArray));
+ assertEquals(Integer.TYPE, newArray.getClass().getComponentType());
+ newArray = ArrayUtils.add(array1, 4);
+ assertTrue(Arrays.equals(new int[]{1, 2, 3, 4}, newArray));
+ assertEquals(Integer.TYPE, newArray.getClass().getComponentType());
+ }
+
+ @Test
+ public void testAddObjectArrayLong() {
+ long[] newArray;
+ newArray = ArrayUtils.add((long[])null, 0);
+ assertTrue(Arrays.equals(new long[]{0}, newArray));
+ assertEquals(Long.TYPE, newArray.getClass().getComponentType());
+ newArray = ArrayUtils.add((long[])null, 1);
+ assertTrue(Arrays.equals(new long[]{1}, newArray));
+ assertEquals(Long.TYPE, newArray.getClass().getComponentType());
+ long[] array1 = new long[]{1, 2, 3};
+ newArray = ArrayUtils.add(array1, 0);
+ assertTrue(Arrays.equals(new long[]{1, 2, 3, 0}, newArray));
+ assertEquals(Long.TYPE, newArray.getClass().getComponentType());
+ newArray = ArrayUtils.add(array1, 4);
+ assertTrue(Arrays.equals(new long[]{1, 2, 3, 4}, newArray));
+ assertEquals(Long.TYPE, newArray.getClass().getComponentType());
+ }
+
+ @Test
+ public void testAddObjectArrayShort() {
+ short[] newArray;
+ newArray = ArrayUtils.add((short[])null, (short)0);
+ assertTrue(Arrays.equals(new short[]{0}, newArray));
+ assertEquals(Short.TYPE, newArray.getClass().getComponentType());
+ newArray = ArrayUtils.add((short[])null, (short)1);
+ assertTrue(Arrays.equals(new short[]{1}, newArray));
+ assertEquals(Short.TYPE, newArray.getClass().getComponentType());
+ short[] array1 = new short[]{1, 2, 3};
+ newArray = ArrayUtils.add(array1, (short)0);
+ assertTrue(Arrays.equals(new short[]{1, 2, 3, 0}, newArray));
+ assertEquals(Short.TYPE, newArray.getClass().getComponentType());
+ newArray = ArrayUtils.add(array1, (short)4);
+ assertTrue(Arrays.equals(new short[]{1, 2, 3, 4}, newArray));
+ assertEquals(Short.TYPE, newArray.getClass().getComponentType());
+ }
+
+ @Test
+ public void testAddObjectArrayObject() {
+ Object[] newArray;
+
+ //show that not casting is okay
+ newArray = ArrayUtils.add((Object[])null, "a");
+ assertTrue(Arrays.equals(new String[]{"a"}, newArray));
+ assertTrue(Arrays.equals(new Object[]{"a"}, newArray));
+ assertEquals(String.class, newArray.getClass().getComponentType());
+
+ //show that not casting to Object[] is okay and will assume String based on "a"
+ String[] newStringArray = ArrayUtils.add(null, "a");
+ assertTrue(Arrays.equals(new String[]{"a"}, newStringArray));
+ assertTrue(Arrays.equals(new Object[]{"a"}, newStringArray));
+ assertEquals(String.class, newStringArray.getClass().getComponentType());
+
+ String[] stringArray1 = new String[]{"a", "b", "c"};
+ newArray = ArrayUtils.add(stringArray1, null);
+ assertTrue(Arrays.equals(new String[]{"a", "b", "c", null}, newArray));
+ assertEquals(String.class, newArray.getClass().getComponentType());
+
+ newArray = ArrayUtils.add(stringArray1, "d");
+ assertTrue(Arrays.equals(new String[]{"a", "b", "c", "d"}, newArray));
+ assertEquals(String.class, newArray.getClass().getComponentType());
+
+ Number[] numberArray1 = new Number[]{Integer.valueOf(1), Double.valueOf(2)};
+ newArray = ArrayUtils.add(numberArray1, Float.valueOf(3));
+ assertTrue(Arrays.equals(new Number[]{Integer.valueOf(1), Double.valueOf(2), Float.valueOf(3)}, newArray));
+ assertEquals(Number.class, newArray.getClass().getComponentType());
+
+ numberArray1 = null;
+ newArray = ArrayUtils.add(numberArray1, Float.valueOf(3));
+ assertTrue(Arrays.equals(new Float[]{Float.valueOf(3)}, newArray));
+ assertEquals(Float.class, newArray.getClass().getComponentType());
+ }
+
+ @Test
+ public void testLANG571(){
+ String[] stringArray=null;
+ String aString=null;
+ try {
+ @SuppressWarnings("unused")
+ String[] sa = ArrayUtils.add(stringArray, aString);
+ fail("Should have caused IllegalArgumentException");
+ } catch (IllegalArgumentException iae){
+ //expected
+ }
+ try {
+ @SuppressWarnings("unused")
+ String[] sa = ArrayUtils.add(stringArray, 0, aString);
+ fail("Should have caused IllegalArgumentException");
+ } catch (IllegalArgumentException iae){
+ //expected
+ }
+ }
+
+ @Test
+ public void testAddObjectArrayToObjectArray() {
+ assertNull(ArrayUtils.addAll((Object[]) null, (Object[]) null));
+ Object[] newArray;
+ String[] stringArray1 = new String[]{"a", "b", "c"};
+ String[] stringArray2 = new String[]{"1", "2", "3"};
+ newArray = ArrayUtils.addAll(stringArray1, (String[]) null);
+ assertNotSame(stringArray1, newArray);
+ assertTrue(Arrays.equals(stringArray1, newArray));
+ assertTrue(Arrays.equals(new String[]{"a", "b", "c"}, newArray));
+ assertEquals(String.class, newArray.getClass().getComponentType());
+ newArray = ArrayUtils.addAll(null, stringArray2);
+ assertNotSame(stringArray2, newArray);
+ assertTrue(Arrays.equals(stringArray2, newArray));
+ assertTrue(Arrays.equals(new String[]{"1", "2", "3"}, newArray));
+ assertEquals(String.class, newArray.getClass().getComponentType());
+ newArray = ArrayUtils.addAll(stringArray1, stringArray2);
+ assertTrue(Arrays.equals(new String[]{"a", "b", "c", "1", "2", "3"}, newArray));
+ assertEquals(String.class, newArray.getClass().getComponentType());
+ newArray = ArrayUtils.addAll(ArrayUtils.EMPTY_STRING_ARRAY, (String[]) null);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_STRING_ARRAY, newArray));
+ assertTrue(Arrays.equals(new String[]{}, newArray));
+ assertEquals(String.class, newArray.getClass().getComponentType());
+ newArray = ArrayUtils.addAll(null, ArrayUtils.EMPTY_STRING_ARRAY);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_STRING_ARRAY, newArray));
+ assertTrue(Arrays.equals(new String[]{}, newArray));
+ assertEquals(String.class, newArray.getClass().getComponentType());
+ newArray = ArrayUtils.addAll(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.EMPTY_STRING_ARRAY);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_STRING_ARRAY, newArray));
+ assertTrue(Arrays.equals(new String[]{}, newArray));
+ assertEquals(String.class, newArray.getClass().getComponentType());
+ String[] stringArrayNull = new String []{null};
+ newArray = ArrayUtils.addAll(stringArrayNull, stringArrayNull);
+ assertTrue(Arrays.equals(new String[]{null, null}, newArray));
+ assertEquals(String.class, newArray.getClass().getComponentType());
+
+ // boolean
+ assertTrue( Arrays.equals( new boolean[] { true, false, false, true },
+ ArrayUtils.addAll( new boolean[] { true, false }, new boolean[] { false, true } ) ) );
+
+ assertTrue( Arrays.equals( new boolean[] { false, true },
+ ArrayUtils.addAll( null, new boolean[] { false, true } ) ) );
+
+ assertTrue( Arrays.equals( new boolean[] { true, false },
+ ArrayUtils.addAll( new boolean[] { true, false }, null ) ) );
+
+ // char
+ assertTrue( Arrays.equals( new char[] { 'a', 'b', 'c', 'd' },
+ ArrayUtils.addAll( new char[] { 'a', 'b' }, new char[] { 'c', 'd' } ) ) );
+
+ assertTrue( Arrays.equals( new char[] { 'c', 'd' },
+ ArrayUtils.addAll( null, new char[] { 'c', 'd' } ) ) );
+
+ assertTrue( Arrays.equals( new char[] { 'a', 'b' },
+ ArrayUtils.addAll( new char[] { 'a', 'b' }, null ) ) );
+
+ // byte
+ assertTrue( Arrays.equals( new byte[] { (byte) 0, (byte) 1, (byte) 2, (byte) 3 },
+ ArrayUtils.addAll( new byte[] { (byte) 0, (byte) 1 }, new byte[] { (byte) 2, (byte) 3 } ) ) );
+
+ assertTrue( Arrays.equals( new byte[] { (byte) 2, (byte) 3 },
+ ArrayUtils.addAll( null, new byte[] { (byte) 2, (byte) 3 } ) ) );
+
+ assertTrue( Arrays.equals( new byte[] { (byte) 0, (byte) 1 },
+ ArrayUtils.addAll( new byte[] { (byte) 0, (byte) 1 }, null ) ) );
+
+ // short
+ assertTrue( Arrays.equals( new short[] { (short) 10, (short) 20, (short) 30, (short) 40 },
+ ArrayUtils.addAll( new short[] { (short) 10, (short) 20 }, new short[] { (short) 30, (short) 40 } ) ) );
+
+ assertTrue( Arrays.equals( new short[] { (short) 30, (short) 40 },
+ ArrayUtils.addAll( null, new short[] { (short) 30, (short) 40 } ) ) );
+
+ assertTrue( Arrays.equals( new short[] { (short) 10, (short) 20 },
+ ArrayUtils.addAll( new short[] { (short) 10, (short) 20 }, null ) ) );
+
+ // int
+ assertTrue( Arrays.equals( new int[] { 1, 1000, -1000, -1 },
+ ArrayUtils.addAll( new int[] { 1, 1000 }, new int[] { -1000, -1 } ) ) );
+
+ assertTrue( Arrays.equals( new int[] { -1000, -1 },
+ ArrayUtils.addAll( null, new int[] { -1000, -1 } ) ) );
+
+ assertTrue( Arrays.equals( new int[] { 1, 1000 },
+ ArrayUtils.addAll( new int[] { 1, 1000 }, null ) ) );
+
+ // long
+ assertTrue( Arrays.equals( new long[] { 1L, -1L, 1000L, -1000L },
+ ArrayUtils.addAll( new long[] { 1L, -1L }, new long[] { 1000L, -1000L } ) ) );
+
+ assertTrue( Arrays.equals( new long[] { 1000L, -1000L },
+ ArrayUtils.addAll( null, new long[] { 1000L, -1000L } ) ) );
+
+ assertTrue( Arrays.equals( new long[] { 1L, -1L },
+ ArrayUtils.addAll( new long[] { 1L, -1L }, null ) ) );
+
+ // float
+ assertTrue( Arrays.equals( new float[] { 10.5f, 10.1f, 1.6f, 0.01f },
+ ArrayUtils.addAll( new float[] { 10.5f, 10.1f }, new float[] { 1.6f, 0.01f } ) ) );
+
+ assertTrue( Arrays.equals( new float[] { 1.6f, 0.01f },
+ ArrayUtils.addAll( null, new float[] { 1.6f, 0.01f } ) ) );
+
+ assertTrue( Arrays.equals( new float[] { 10.5f, 10.1f },
+ ArrayUtils.addAll( new float[] { 10.5f, 10.1f }, null ) ) );
+
+ // double
+ assertTrue( Arrays.equals( new double[] { Math.PI, -Math.PI, 0, 9.99 },
+ ArrayUtils.addAll( new double[] { Math.PI, -Math.PI }, new double[] { 0, 9.99 } ) ) );
+
+ assertTrue( Arrays.equals( new double[] { 0, 9.99 },
+ ArrayUtils.addAll( null, new double[] { 0, 9.99 } ) ) );
+
+ assertTrue( Arrays.equals( new double[] { Math.PI, -Math.PI },
+ ArrayUtils.addAll( new double[] { Math.PI, -Math.PI }, null ) ) );
+
+ }
+
+ @Test
+ public void testAddObjectAtIndex() {
+ Object[] newArray;
+ newArray = ArrayUtils.add((Object[])null, 0, "a");
+ assertTrue(Arrays.equals(new String[]{"a"}, newArray));
+ assertTrue(Arrays.equals(new Object[]{"a"}, newArray));
+ assertEquals(String.class, newArray.getClass().getComponentType());
+ String[] stringArray1 = new String[]{"a", "b", "c"};
+ newArray = ArrayUtils.add(stringArray1, 0, null);
+ assertTrue(Arrays.equals(new String[]{null, "a", "b", "c"}, newArray));
+ assertEquals(String.class, newArray.getClass().getComponentType());
+ newArray = ArrayUtils.add(stringArray1, 1, null);
+ assertTrue(Arrays.equals(new String[]{"a", null, "b", "c"}, newArray));
+ assertEquals(String.class, newArray.getClass().getComponentType());
+ newArray = ArrayUtils.add(stringArray1, 3, null);
+ assertTrue(Arrays.equals(new String[]{"a", "b", "c", null}, newArray));
+ assertEquals(String.class, newArray.getClass().getComponentType());
+ newArray = ArrayUtils.add(stringArray1, 3, "d");
+ assertTrue(Arrays.equals(new String[]{"a", "b", "c", "d"}, newArray));
+ assertEquals(String.class, newArray.getClass().getComponentType());
+ assertEquals(String.class, newArray.getClass().getComponentType());
+
+ Object[] o = new Object[] {"1", "2", "4"};
+ Object[] result = ArrayUtils.add(o, 2, "3");
+ Object[] result2 = ArrayUtils.add(o, 3, "5");
+
+ assertNotNull(result);
+ assertEquals(4, result.length);
+ assertEquals("1", result[0]);
+ assertEquals("2", result[1]);
+ assertEquals("3", result[2]);
+ assertEquals("4", result[3]);
+ assertNotNull(result2);
+ assertEquals(4, result2.length);
+ assertEquals("1", result2[0]);
+ assertEquals("2", result2[1]);
+ assertEquals("4", result2[2]);
+ assertEquals("5", result2[3]);
+
+ // boolean tests
+ boolean[] booleanArray = ArrayUtils.add( null, 0, true );
+ assertTrue( Arrays.equals( new boolean[] { true }, booleanArray ) );
+ try {
+ booleanArray = ArrayUtils.add( null, -1, true );
+ } catch(IndexOutOfBoundsException e) {
+ assertEquals("Index: -1, Length: 0", e.getMessage());
+ }
+ booleanArray = ArrayUtils.add( new boolean[] { true }, 0, false);
+ assertTrue( Arrays.equals( new boolean[] { false, true }, booleanArray ) );
+ booleanArray = ArrayUtils.add( new boolean[] { false }, 1, true);
+ assertTrue( Arrays.equals( new boolean[] { false, true }, booleanArray ) );
+ booleanArray = ArrayUtils.add( new boolean[] { true, false }, 1, true);
+ assertTrue( Arrays.equals( new boolean[] { true, true, false }, booleanArray ) );
+ try {
+ booleanArray = ArrayUtils.add( new boolean[] { true, false }, 4, true);
+ } catch(IndexOutOfBoundsException e) {
+ assertEquals("Index: 4, Length: 2", e.getMessage());
+ }
+ try {
+ booleanArray = ArrayUtils.add( new boolean[] { true, false }, -1, true);
+ } catch(IndexOutOfBoundsException e) {
+ assertEquals("Index: -1, Length: 2", e.getMessage());
+ }
+
+ // char tests
+ char[] charArray = ArrayUtils.add( (char[]) null, 0, 'a' );
+ assertTrue( Arrays.equals( new char[] { 'a' }, charArray ) );
+ try {
+ charArray = ArrayUtils.add( (char[]) null, -1, 'a' );
+ } catch(IndexOutOfBoundsException e) {
+ assertEquals("Index: -1, Length: 0", e.getMessage());
+ }
+ charArray = ArrayUtils.add( new char[] { 'a' }, 0, 'b');
+ assertTrue( Arrays.equals( new char[] { 'b', 'a' }, charArray ) );
+ charArray = ArrayUtils.add( new char[] { 'a', 'b' }, 0, 'c');
+ assertTrue( Arrays.equals( new char[] { 'c', 'a', 'b' }, charArray ) );
+ charArray = ArrayUtils.add( new char[] { 'a', 'b' }, 1, 'k');
+ assertTrue( Arrays.equals( new char[] { 'a', 'k', 'b' }, charArray ) );
+ charArray = ArrayUtils.add( new char[] { 'a', 'b', 'c' }, 1, 't');
+ assertTrue( Arrays.equals( new char[] { 'a', 't', 'b', 'c' }, charArray ) );
+ try {
+ charArray = ArrayUtils.add( new char[] { 'a', 'b' }, 4, 'c');
+ } catch(IndexOutOfBoundsException e) {
+ assertEquals("Index: 4, Length: 2", e.getMessage());
+ }
+ try {
+ charArray = ArrayUtils.add( new char[] { 'a', 'b' }, -1, 'c');
+ } catch(IndexOutOfBoundsException e) {
+ assertEquals("Index: -1, Length: 2", e.getMessage());
+ }
+
+ // short tests
+ short[] shortArray = ArrayUtils.add( new short[] { 1 }, 0, (short) 2);
+ assertTrue( Arrays.equals( new short[] { 2, 1 }, shortArray ) );
+ try {
+ shortArray = ArrayUtils.add( (short[]) null, -1, (short) 2);
+ } catch(IndexOutOfBoundsException e) {
+ assertEquals("Index: -1, Length: 0", e.getMessage());
+ }
+ shortArray = ArrayUtils.add( new short[] { 2, 6 }, 2, (short) 10);
+ assertTrue( Arrays.equals( new short[] { 2, 6, 10 }, shortArray ) );
+ shortArray = ArrayUtils.add( new short[] { 2, 6 }, 0, (short) -4);
+ assertTrue( Arrays.equals( new short[] { -4, 2, 6 }, shortArray ) );
+ shortArray = ArrayUtils.add( new short[] { 2, 6, 3 }, 2, (short) 1);
+ assertTrue( Arrays.equals( new short[] { 2, 6, 1, 3 }, shortArray ) );
+ try {
+ shortArray = ArrayUtils.add( new short[] { 2, 6 }, 4, (short) 10);
+ } catch(IndexOutOfBoundsException e) {
+ assertEquals("Index: 4, Length: 2", e.getMessage());
+ }
+ try {
+ shortArray = ArrayUtils.add( new short[] { 2, 6 }, -1, (short) 10);
+ } catch(IndexOutOfBoundsException e) {
+ assertEquals("Index: -1, Length: 2", e.getMessage());
+ }
+
+ // byte tests
+ byte[] byteArray = ArrayUtils.add( new byte[] { 1 }, 0, (byte) 2);
+ assertTrue( Arrays.equals( new byte[] { 2, 1 }, byteArray ) );
+ try {
+ byteArray = ArrayUtils.add( (byte[]) null, -1, (byte) 2);
+ } catch(IndexOutOfBoundsException e) {
+ assertEquals("Index: -1, Length: 0", e.getMessage());
+ }
+ byteArray = ArrayUtils.add( new byte[] { 2, 6 }, 2, (byte) 3);
+ assertTrue( Arrays.equals( new byte[] { 2, 6, 3 }, byteArray ) );
+ byteArray = ArrayUtils.add( new byte[] { 2, 6 }, 0, (byte) 1);
+ assertTrue( Arrays.equals( new byte[] { 1, 2, 6 }, byteArray ) );
+ byteArray = ArrayUtils.add( new byte[] { 2, 6, 3 }, 2, (byte) 1);
+ assertTrue( Arrays.equals( new byte[] { 2, 6, 1, 3 }, byteArray ) );
+ try {
+ byteArray = ArrayUtils.add( new byte[] { 2, 6 }, 4, (byte) 3);
+ } catch(IndexOutOfBoundsException e) {
+ assertEquals("Index: 4, Length: 2", e.getMessage());
+ }
+ try {
+ byteArray = ArrayUtils.add( new byte[] { 2, 6 }, -1, (byte) 3);
+ } catch(IndexOutOfBoundsException e) {
+ assertEquals("Index: -1, Length: 2", e.getMessage());
+ }
+
+ // int tests
+ int[] intArray = ArrayUtils.add( new int[] { 1 }, 0, 2);
+ assertTrue( Arrays.equals( new int[] { 2, 1 }, intArray ) );
+ try {
+ intArray = ArrayUtils.add( (int[]) null, -1, 2);
+ } catch(IndexOutOfBoundsException e) {
+ assertEquals("Index: -1, Length: 0", e.getMessage());
+ }
+ intArray = ArrayUtils.add( new int[] { 2, 6 }, 2, 10);
+ assertTrue( Arrays.equals( new int[] { 2, 6, 10 }, intArray ) );
+ intArray = ArrayUtils.add( new int[] { 2, 6 }, 0, -4);
+ assertTrue( Arrays.equals( new int[] { -4, 2, 6 }, intArray ) );
+ intArray = ArrayUtils.add( new int[] { 2, 6, 3 }, 2, 1);
+ assertTrue( Arrays.equals( new int[] { 2, 6, 1, 3 }, intArray ) );
+ try {
+ intArray = ArrayUtils.add( new int[] { 2, 6 }, 4, 10);
+ } catch(IndexOutOfBoundsException e) {
+ assertEquals("Index: 4, Length: 2", e.getMessage());
+ }
+ try {
+ intArray = ArrayUtils.add( new int[] { 2, 6 }, -1, 10);
+ } catch(IndexOutOfBoundsException e) {
+ assertEquals("Index: -1, Length: 2", e.getMessage());
+ }
+
+ // long tests
+ long[] longArray = ArrayUtils.add( new long[] { 1L }, 0, 2L);
+ assertTrue( Arrays.equals( new long[] { 2L, 1L }, longArray ) );
+ try {
+ longArray = ArrayUtils.add( (long[]) null, -1, 2L);
+ } catch(IndexOutOfBoundsException e) {
+ assertEquals("Index: -1, Length: 0", e.getMessage());
+ }
+ longArray = ArrayUtils.add( new long[] { 2L, 6L }, 2, 10L);
+ assertTrue( Arrays.equals( new long[] { 2L, 6L, 10L }, longArray ) );
+ longArray = ArrayUtils.add( new long[] { 2L, 6L }, 0, -4L);
+ assertTrue( Arrays.equals( new long[] { -4L, 2L, 6L }, longArray ) );
+ longArray = ArrayUtils.add( new long[] { 2L, 6L, 3L }, 2, 1L);
+ assertTrue( Arrays.equals( new long[] { 2L, 6L, 1L, 3L }, longArray ) );
+ try {
+ longArray = ArrayUtils.add( new long[] { 2L, 6L }, 4, 10L);
+ } catch(IndexOutOfBoundsException e) {
+ assertEquals("Index: 4, Length: 2", e.getMessage());
+ }
+ try {
+ longArray = ArrayUtils.add( new long[] { 2L, 6L }, -1, 10L);
+ } catch(IndexOutOfBoundsException e) {
+ assertEquals("Index: -1, Length: 2", e.getMessage());
+ }
+
+ // float tests
+ float[] floatArray = ArrayUtils.add( new float[] { 1.1f }, 0, 2.2f);
+ assertTrue( Arrays.equals( new float[] { 2.2f, 1.1f }, floatArray ) );
+ try {
+ floatArray = ArrayUtils.add( (float[]) null, -1, 2.2f);
+ } catch(IndexOutOfBoundsException e) {
+ assertEquals("Index: -1, Length: 0", e.getMessage());
+ }
+ floatArray = ArrayUtils.add( new float[] { 2.3f, 6.4f }, 2, 10.5f);
+ assertTrue( Arrays.equals( new float[] { 2.3f, 6.4f, 10.5f }, floatArray ) );
+ floatArray = ArrayUtils.add( new float[] { 2.6f, 6.7f }, 0, -4.8f);
+ assertTrue( Arrays.equals( new float[] { -4.8f, 2.6f, 6.7f }, floatArray ) );
+ floatArray = ArrayUtils.add( new float[] { 2.9f, 6.0f, 0.3f }, 2, 1.0f);
+ assertTrue( Arrays.equals( new float[] { 2.9f, 6.0f, 1.0f, 0.3f }, floatArray ) );
+ try {
+ floatArray = ArrayUtils.add( new float[] { 2.3f, 6.4f }, 4, 10.5f);
+ } catch(IndexOutOfBoundsException e) {
+ assertEquals("Index: 4, Length: 2", e.getMessage());
+ }
+ try {
+ floatArray = ArrayUtils.add( new float[] { 2.3f, 6.4f }, -1, 10.5f);
+ } catch(IndexOutOfBoundsException e) {
+ assertEquals("Index: -1, Length: 2", e.getMessage());
+ }
+
+ // double tests
+ double[] doubleArray = ArrayUtils.add( new double[] { 1.1 }, 0, 2.2);
+ assertTrue( Arrays.equals( new double[] { 2.2, 1.1 }, doubleArray ) );
+ try {
+ doubleArray = ArrayUtils.add( (double[]) null, -1, 2.2);
+ } catch(IndexOutOfBoundsException e) {
+ assertEquals("Index: -1, Length: 0", e.getMessage());
+ }
+ doubleArray = ArrayUtils.add( new double[] { 2.3, 6.4 }, 2, 10.5);
+ assertTrue( Arrays.equals( new double[] { 2.3, 6.4, 10.5 }, doubleArray ) );
+ doubleArray = ArrayUtils.add( new double[] { 2.6, 6.7 }, 0, -4.8);
+ assertTrue( Arrays.equals( new double[] { -4.8, 2.6, 6.7 }, doubleArray ) );
+ doubleArray = ArrayUtils.add( new double[] { 2.9, 6.0, 0.3 }, 2, 1.0);
+ assertTrue( Arrays.equals( new double[] { 2.9, 6.0, 1.0, 0.3 }, doubleArray ) );
+ try {
+ doubleArray = ArrayUtils.add( new double[] { 2.3, 6.4 }, 4, 10.5);
+ } catch(IndexOutOfBoundsException e) {
+ assertEquals("Index: 4, Length: 2", e.getMessage());
+ }
+ try {
+ doubleArray = ArrayUtils.add( new double[] { 2.3, 6.4 }, -1, 10.5);
+ } catch(IndexOutOfBoundsException e) {
+ assertEquals("Index: -1, Length: 2", e.getMessage());
+ }
+ }
+
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/ArrayUtilsRemoveMultipleTest.java b/ApacheCommonsLang/org/apache/commons/lang3/ArrayUtilsRemoveMultipleTest.java
new file mode 100644
index 0000000..8c26c13
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/ArrayUtilsRemoveMultipleTest.java
@@ -0,0 +1,1049 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+package org.apache.commons.lang3;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Arrays;
+
+import org.junit.Test;
+
+/**
+ * Tests ArrayUtils remove and removeElement methods.
+ *
+ * @version $Id: ArrayUtilsRemoveMultipleTest.java 1309910 2012-04-05 15:52:43Z ggregory $
+ */
+public class ArrayUtilsRemoveMultipleTest {
+
+ @Test
+ public void testRemoveAllObjectArray() {
+ Object[] array;
+ array = ArrayUtils.removeAll(new Object[] { "a" }, 0);
+ assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array);
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new Object[] { "a", "b" }, 0, 1);
+ assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array);
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new Object[] { "a", "b", "c" }, 1, 2);
+ assertArrayEquals(new Object[] { "a" }, array);
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new Object[] { "a", "b", "c", "d" }, 1, 2);
+ assertArrayEquals(new Object[] { "a", "d" }, array);
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new Object[] { "a", "b", "c", "d" }, 0, 3);
+ assertArrayEquals(new Object[] { "b", "c" }, array);
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new Object[] { "a", "b", "c", "d" }, 0, 1, 3);
+ assertArrayEquals(new Object[] { "c" }, array);
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new Object[] { "a", "b", "c", "d", "e" }, 0, 1, 3);
+ assertArrayEquals(new Object[] { "c", "e" }, array);
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new Object[] { "a", "b", "c", "d", "e" }, 0, 2, 4);
+ assertArrayEquals(new Object[] { "b", "d" }, array);
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new Object[] { "a", "b", "c", "d" }, 0, 1, 3, 0, 1, 3);
+ assertArrayEquals(new Object[] { "c" }, array);
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new Object[] { "a", "b", "c", "d" }, 2, 1, 0, 3);
+ assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array);
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new Object[] { "a", "b", "c", "d" }, 2, 0, 1, 3, 0, 2, 1, 3);
+ assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array);
+ assertEquals(Object.class, array.getClass().getComponentType());
+ }
+
+ @Test
+ public void testRemoveAllObjectArrayRemoveNone() {
+ Object[] array1 = new Object[] { "foo", "bar", "baz" };
+ Object[] array2 = ArrayUtils.removeAll(array1);
+ assertNotSame(array1, array2);
+ assertArrayEquals(array1, array2);
+ assertEquals(Object.class, array2.getClass().getComponentType());
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllObjectArrayNegativeIndex() {
+ ArrayUtils.removeAll(new Object[] { "a", "b" }, -1);
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllObjectArrayOutOfBoundsIndex() {
+ ArrayUtils.removeAll(new Object[] { "a", "b" }, 2);
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllNullObjectArray() {
+ ArrayUtils.remove((Object[]) null, 0);
+ }
+
+ @Test
+ public void testRemoveAllNumberArray() {
+ Number[] inarray = { Integer.valueOf(1), Long.valueOf(2L), Byte.valueOf((byte) 3) };
+ assertEquals(3, inarray.length);
+ Number[] outarray;
+ outarray = ArrayUtils.removeAll(inarray, 1);
+ assertArrayEquals(new Number[] { Integer.valueOf(1), Byte.valueOf((byte) 3) }, outarray);
+ assertEquals(Number.class, outarray.getClass().getComponentType());
+ outarray = ArrayUtils.removeAll(outarray, 1);
+ assertArrayEquals(new Number[] { Integer.valueOf(1) }, outarray);
+ assertEquals(Number.class, outarray.getClass().getComponentType());
+ outarray = ArrayUtils.removeAll(outarray, 0);
+ assertEquals(0, outarray.length);
+ assertEquals(Number.class, outarray.getClass().getComponentType());
+
+ outarray = ArrayUtils.removeAll(inarray, 0, 1);
+ assertArrayEquals(new Number[] { Byte.valueOf((byte) 3) }, outarray);
+ assertEquals(Number.class, outarray.getClass().getComponentType());
+ outarray = ArrayUtils.removeAll(inarray, 0, 2);
+ assertArrayEquals(new Number[] { Long.valueOf(2L) }, outarray);
+ assertEquals(Number.class, outarray.getClass().getComponentType());
+ outarray = ArrayUtils.removeAll(inarray, 1, 2);
+ assertArrayEquals(new Number[] { Integer.valueOf(1) }, outarray);
+ assertEquals(Number.class, outarray.getClass().getComponentType());
+ }
+
+ @Test
+ public void testRemoveAllBooleanArray() {
+ boolean[] array;
+ array = ArrayUtils.removeAll(new boolean[] { true }, 0);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new boolean[] { true, false }, 0);
+ assertTrue(Arrays.equals(new boolean[] { false }, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new boolean[] { true, false }, 1);
+ assertTrue(Arrays.equals(new boolean[] { true }, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new boolean[] { true, false, true }, 1);
+ assertTrue(Arrays.equals(new boolean[] { true, true }, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+
+ array = ArrayUtils.removeAll(new boolean[] { true, false }, 0, 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new boolean[] { true, false, false }, 0, 1);
+ assertTrue(Arrays.equals(new boolean[] { false }, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new boolean[] { true, false, false }, 0, 2);
+ assertTrue(Arrays.equals(new boolean[] { false }, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new boolean[] { true, false, false }, 1, 2);
+ assertTrue(Arrays.equals(new boolean[] { true }, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new boolean[] { true, false, true, false, true }, 0, 2, 4);
+ assertTrue(Arrays.equals(new boolean[] { false, false }, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new boolean[] { true, false, true, false, true }, 1, 3);
+ assertTrue(Arrays.equals(new boolean[] { true, true, true }, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new boolean[] { true, false, true, false, true }, 1, 3, 4);
+ assertTrue(Arrays.equals(new boolean[] { true, true }, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new boolean[] { true, false, true, false, true, false, true }, 0, 2, 4, 6);
+ assertTrue(Arrays.equals(new boolean[] { false, false, false }, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new boolean[] { true, false, true, false, true, false, true }, 1, 3, 5);
+ assertTrue(Arrays.equals(new boolean[] { true, true, true, true }, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new boolean[] { true, false, true, false, true, false, true }, 0, 1, 2);
+ assertTrue(Arrays.equals(new boolean[] { false, true, false, true }, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ }
+
+ @Test
+ public void testRemoveAllBooleanArrayRemoveNone() {
+ boolean[] array1 = new boolean[] { true, false };
+ boolean[] array2 = ArrayUtils.removeAll(array1);
+ assertNotSame(array1, array2);
+ assertTrue(Arrays.equals(array1, array2));
+ assertEquals(boolean.class, array2.getClass().getComponentType());
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllBooleanArrayNegativeIndex() {
+ ArrayUtils.removeAll(new boolean[] { true, false }, -1);
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllBooleanArrayOutOfBoundsIndex() {
+ ArrayUtils.removeAll(new boolean[] { true, false }, 2);
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllNullBooleanArray() {
+ ArrayUtils.removeAll((boolean[]) null, 0);
+ }
+
+ @Test
+ public void testRemoveAllByteArray() {
+ byte[] array;
+ array = ArrayUtils.removeAll(new byte[] { 1 }, 0);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_BYTE_ARRAY, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new byte[] { 1, 2 }, 0);
+ assertTrue(Arrays.equals(new byte[] { 2 }, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new byte[] { 1, 2 }, 1);
+ assertTrue(Arrays.equals(new byte[] { 1 }, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new byte[] { 1, 2, 1 }, 1);
+ assertTrue(Arrays.equals(new byte[] { 1, 1 }, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+
+ array = ArrayUtils.removeAll(new byte[] { 1, 2 }, 0, 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_BYTE_ARRAY, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new byte[] { 1, 2, 3 }, 0, 1);
+ assertTrue(Arrays.equals(new byte[] { 3 }, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new byte[] { 1, 2, 3 }, 1, 2);
+ assertTrue(Arrays.equals(new byte[] { 1 }, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new byte[] { 1, 2, 3 }, 0, 2);
+ assertTrue(Arrays.equals(new byte[] { 2 }, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new byte[] { 1, 2, 3, 4, 5 }, 1, 3);
+ assertTrue(Arrays.equals(new byte[] { 1, 3, 5 }, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new byte[] { 1, 2, 3, 4, 5 }, 0, 2, 4);
+ assertTrue(Arrays.equals(new byte[] { 2, 4 }, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new byte[] { 1, 2, 3, 4, 5, 6, 7 }, 1, 3, 5);
+ assertTrue(Arrays.equals(new byte[] { 1, 3, 5, 7 }, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new byte[] { 1, 2, 3, 4, 5, 6, 7 }, 0, 2, 4, 6);
+ assertTrue(Arrays.equals(new byte[] { 2, 4, 6 }, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ }
+
+ @Test
+ public void testRemoveAllByteArrayRemoveNone() {
+ byte[] array1 = new byte[] { 1, 2 };
+ byte[] array2 = ArrayUtils.removeAll(array1);
+ assertNotSame(array1, array2);
+ assertArrayEquals(array1, array2);
+ assertEquals(byte.class, array2.getClass().getComponentType());
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllByteArrayNegativeIndex() {
+ ArrayUtils.removeAll(new byte[] { 1, 2 }, -1);
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllByteArrayOutOfBoundsIndex() {
+ ArrayUtils.removeAll(new byte[] { 1, 2 }, 2);
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllNullByteArray() {
+ ArrayUtils.removeAll((byte[]) null, 0);
+ }
+
+ @Test
+ public void testRemoveAllCharArray() {
+ char[] array;
+ array = ArrayUtils.removeAll(new char[] { 'a' }, 0);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_CHAR_ARRAY, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new char[] { 'a', 'b' }, 0);
+ assertTrue(Arrays.equals(new char[] { 'b' }, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new char[] { 'a', 'b' }, 1);
+ assertTrue(Arrays.equals(new char[] { 'a' }, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new char[] { 'a', 'b', 'c' }, 1);
+ assertTrue(Arrays.equals(new char[] { 'a', 'c' }, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+
+ array = ArrayUtils.removeAll(new char[] { 'a', 'b' }, 0, 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_CHAR_ARRAY, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new char[] { 'a', 'b', 'c' }, 0, 1);
+ assertTrue(Arrays.equals(new char[] { 'c' }, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new char[] { 'a', 'b', 'c' }, 1, 2);
+ assertTrue(Arrays.equals(new char[] { 'a' }, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new char[] { 'a', 'b', 'c' }, 0, 2);
+ assertTrue(Arrays.equals(new char[] { 'b' }, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new char[] { 'a', 'b', 'c', 'd', 'e' }, 1, 3);
+ assertTrue(Arrays.equals(new char[] { 'a', 'c', 'e' }, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new char[] { 'a', 'b', 'c', 'd', 'e' }, 0, 2, 4);
+ assertTrue(Arrays.equals(new char[] { 'b', 'd' }, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g' }, 1, 3, 5);
+ assertTrue(Arrays.equals(new char[] { 'a', 'c', 'e', 'g' }, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g' }, 0, 2, 4, 6);
+ assertTrue(Arrays.equals(new char[] { 'b', 'd', 'f' }, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ }
+
+ @Test
+ public void testRemoveAllCharArrayRemoveNone() {
+ char[] array1 = new char[] { 'a', 'b' };
+ char[] array2 = ArrayUtils.removeAll(array1);
+ assertNotSame(array1, array2);
+ assertArrayEquals(array1, array2);
+ assertEquals(char.class, array2.getClass().getComponentType());
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllCharArrayNegativeIndex() {
+ ArrayUtils.removeAll(new char[] { 'a', 'b' }, -1);
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllCharArrayOutOfBoundsIndex() {
+ ArrayUtils.removeAll(new char[] { 'a', 'b' }, 2);
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllNullCharArray() {
+ ArrayUtils.removeAll((char[]) null, 0);
+ }
+
+ @Test
+ public void testRemoveAllDoubleArray() {
+ double[] array;
+ array = ArrayUtils.removeAll(new double[] { 1 }, 0);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_DOUBLE_ARRAY, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new double[] { 1, 2 }, 0);
+ assertTrue(Arrays.equals(new double[] { 2 }, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new double[] { 1, 2 }, 1);
+ assertTrue(Arrays.equals(new double[] { 1 }, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new double[] { 1, 2, 1 }, 1);
+ assertTrue(Arrays.equals(new double[] { 1, 1 }, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+
+ array = ArrayUtils.removeAll(new double[] { 1, 2 }, 0, 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_DOUBLE_ARRAY, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new double[] { 1, 2, 3 }, 0, 1);
+ assertTrue(Arrays.equals(new double[] { 3 }, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new double[] { 1, 2, 3 }, 1, 2);
+ assertTrue(Arrays.equals(new double[] { 1 }, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new double[] { 1, 2, 3 }, 0, 2);
+ assertTrue(Arrays.equals(new double[] { 2 }, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new double[] { 1, 2, 3, 4, 5 }, 1, 3);
+ assertTrue(Arrays.equals(new double[] { 1, 3, 5 }, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new double[] { 1, 2, 3, 4, 5 }, 0, 2, 4);
+ assertTrue(Arrays.equals(new double[] { 2, 4 }, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new double[] { 1, 2, 3, 4, 5, 6, 7 }, 1, 3, 5);
+ assertTrue(Arrays.equals(new double[] { 1, 3, 5, 7 }, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new double[] { 1, 2, 3, 4, 5, 6, 7 }, 0, 2, 4, 6);
+ assertTrue(Arrays.equals(new double[] { 2, 4, 6 }, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ }
+
+ @Test
+ public void testRemoveAllDoubleArrayRemoveNone() {
+ double[] array1 = new double[] { 1, 2 };
+ double[] array2 = ArrayUtils.removeAll(array1);
+ assertNotSame(array1, array2);
+ assertTrue(Arrays.equals(array1, array2));
+ assertEquals(double.class, array2.getClass().getComponentType());
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllDoubleArrayNegativeIndex() {
+ ArrayUtils.removeAll(new double[] { 1, 2 }, -1);
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllDoubleArrayOutOfBoundsIndex() {
+ ArrayUtils.removeAll(new double[] { 1, 2 }, 2);
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllNullDoubleArray() {
+ ArrayUtils.removeAll((double[]) null, 0);
+ }
+
+ @Test
+ public void testRemoveAllFloatArray() {
+ float[] array;
+ array = ArrayUtils.removeAll(new float[] { 1 }, 0);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_FLOAT_ARRAY, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new float[] { 1, 2 }, 0);
+ assertTrue(Arrays.equals(new float[] { 2 }, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new float[] { 1, 2 }, 1);
+ assertTrue(Arrays.equals(new float[] { 1 }, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new float[] { 1, 2, 1 }, 1);
+ assertTrue(Arrays.equals(new float[] { 1, 1 }, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+
+ array = ArrayUtils.removeAll(new float[] { 1, 2 }, 0, 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_FLOAT_ARRAY, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new float[] { 1, 2, 3 }, 0, 1);
+ assertTrue(Arrays.equals(new float[] { 3 }, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new float[] { 1, 2, 3 }, 1, 2);
+ assertTrue(Arrays.equals(new float[] { 1 }, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new float[] { 1, 2, 3 }, 0, 2);
+ assertTrue(Arrays.equals(new float[] { 2 }, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new float[] { 1, 2, 3, 4, 5 }, 1, 3);
+ assertTrue(Arrays.equals(new float[] { 1, 3, 5 }, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new float[] { 1, 2, 3, 4, 5 }, 0, 2, 4);
+ assertTrue(Arrays.equals(new float[] { 2, 4 }, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new float[] { 1, 2, 3, 4, 5, 6, 7 }, 1, 3, 5);
+ assertTrue(Arrays.equals(new float[] { 1, 3, 5, 7 }, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new float[] { 1, 2, 3, 4, 5, 6, 7 }, 0, 2, 4, 6);
+ assertTrue(Arrays.equals(new float[] { 2, 4, 6 }, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ }
+
+ @Test
+ public void testRemoveAllFloatArrayRemoveNone() {
+ float[] array1 = new float[] { 1, 2 };
+ float[] array2 = ArrayUtils.removeAll(array1);
+ assertNotSame(array1, array2);
+ assertTrue(Arrays.equals(array1, array2));
+ assertEquals(float.class, array2.getClass().getComponentType());
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllFloatArrayNegativeIndex() {
+ ArrayUtils.removeAll(new float[] { 1, 2 }, -1);
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllFloatArrayOutOfBoundsIndex() {
+ ArrayUtils.removeAll(new float[] { 1, 2 }, 2);
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllNullFloatArray() {
+ ArrayUtils.removeAll((float[]) null, 0);
+ }
+
+ @Test
+ public void testRemoveAllIntArray() {
+ int[] array;
+ array = ArrayUtils.removeAll(new int[] { 1 }, 0);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_INT_ARRAY, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new int[] { 1, 2 }, 0);
+ assertTrue(Arrays.equals(new int[] { 2 }, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new int[] { 1, 2 }, 1);
+ assertTrue(Arrays.equals(new int[] { 1 }, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new int[] { 1, 2, 1 }, 1);
+ assertTrue(Arrays.equals(new int[] { 1, 1 }, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+
+ array = ArrayUtils.removeAll(new int[] { 1, 2 }, 0, 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_INT_ARRAY, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new int[] { 1, 2, 3 }, 0, 1);
+ assertTrue(Arrays.equals(new int[] { 3 }, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new int[] { 1, 2, 3 }, 1, 2);
+ assertTrue(Arrays.equals(new int[] { 1 }, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new int[] { 1, 2, 3 }, 0, 2);
+ assertTrue(Arrays.equals(new int[] { 2 }, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new int[] { 1, 2, 3, 4, 5 }, 1, 3);
+ assertTrue(Arrays.equals(new int[] { 1, 3, 5 }, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new int[] { 1, 2, 3, 4, 5 }, 0, 2, 4);
+ assertTrue(Arrays.equals(new int[] { 2, 4 }, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new int[] { 1, 2, 3, 4, 5, 6, 7 }, 1, 3, 5);
+ assertTrue(Arrays.equals(new int[] { 1, 3, 5, 7 }, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new int[] { 1, 2, 3, 4, 5, 6, 7 }, 0, 2, 4, 6);
+ assertTrue(Arrays.equals(new int[] { 2, 4, 6 }, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ }
+
+ @Test
+ public void testRemoveAllIntArrayRemoveNone() {
+ int[] array1 = new int[] { 1, 2 };
+ int[] array2 = ArrayUtils.removeAll(array1);
+ assertNotSame(array1, array2);
+ assertArrayEquals(array1, array2);
+ assertEquals(int.class, array2.getClass().getComponentType());
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllIntArrayNegativeIndex() {
+ ArrayUtils.removeAll(new int[] { 1, 2 }, -1);
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllIntArrayOutOfBoundsIndex() {
+ ArrayUtils.removeAll(new int[] { 1, 2 }, 2);
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllNullIntArray() {
+ ArrayUtils.removeAll((int[]) null, 0);
+ }
+
+ @Test
+ public void testRemoveAllLongArray() {
+ long[] array;
+ array = ArrayUtils.removeAll(new long[] { 1 }, 0);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_LONG_ARRAY, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new long[] { 1, 2 }, 0);
+ assertTrue(Arrays.equals(new long[] { 2 }, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new long[] { 1, 2 }, 1);
+ assertTrue(Arrays.equals(new long[] { 1 }, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new long[] { 1, 2, 1 }, 1);
+ assertTrue(Arrays.equals(new long[] { 1, 1 }, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+
+ array = ArrayUtils.removeAll(new long[] { 1, 2 }, 0, 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_LONG_ARRAY, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new long[] { 1, 2, 3 }, 0, 1);
+ assertTrue(Arrays.equals(new long[] { 3 }, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new long[] { 1, 2, 3 }, 1, 2);
+ assertTrue(Arrays.equals(new long[] { 1 }, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new long[] { 1, 2, 3 }, 0, 2);
+ assertTrue(Arrays.equals(new long[] { 2 }, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new long[] { 1, 2, 3, 4, 5 }, 1, 3);
+ assertTrue(Arrays.equals(new long[] { 1, 3, 5 }, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new long[] { 1, 2, 3, 4, 5 }, 0, 2, 4);
+ assertTrue(Arrays.equals(new long[] { 2, 4 }, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new long[] { 1, 2, 3, 4, 5, 6, 7 }, 1, 3, 5);
+ assertTrue(Arrays.equals(new long[] { 1, 3, 5, 7 }, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new long[] { 1, 2, 3, 4, 5, 6, 7 }, 0, 2, 4, 6);
+ assertTrue(Arrays.equals(new long[] { 2, 4, 6 }, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ }
+
+ @Test
+ public void testRemoveAllLongArrayRemoveNone() {
+ long[] array1 = new long[] { 1, 2 };
+ long[] array2 = ArrayUtils.removeAll(array1);
+ assertNotSame(array1, array2);
+ assertArrayEquals(array1, array2);
+ assertEquals(long.class, array2.getClass().getComponentType());
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllLongArrayNegativeIndex() {
+ ArrayUtils.removeAll(new long[] { 1, 2 }, -1);
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllLongArrayOutOfBoundsIndex() {
+ ArrayUtils.removeAll(new long[] { 1, 2 }, 2);
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllNullLongArray() {
+ ArrayUtils.removeAll((long[]) null, 0);
+ }
+
+ @Test
+ public void testRemoveAllShortArray() {
+ short[] array;
+ array = ArrayUtils.removeAll(new short[] { 1 }, 0);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_SHORT_ARRAY, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new short[] { 1, 2 }, 0);
+ assertTrue(Arrays.equals(new short[] { 2 }, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new short[] { 1, 2 }, 1);
+ assertTrue(Arrays.equals(new short[] { 1 }, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new short[] { 1, 2, 1 }, 1);
+ assertTrue(Arrays.equals(new short[] { 1, 1 }, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+
+ array = ArrayUtils.removeAll(new short[] { 1, 2 }, 0, 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_SHORT_ARRAY, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new short[] { 1, 2, 3 }, 0, 1);
+ assertTrue(Arrays.equals(new short[] { 3 }, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new short[] { 1, 2, 3 }, 1, 2);
+ assertTrue(Arrays.equals(new short[] { 1 }, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new short[] { 1, 2, 3 }, 0, 2);
+ assertTrue(Arrays.equals(new short[] { 2 }, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new short[] { 1, 2, 3, 4, 5 }, 1, 3);
+ assertTrue(Arrays.equals(new short[] { 1, 3, 5 }, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new short[] { 1, 2, 3, 4, 5 }, 0, 2, 4);
+ assertTrue(Arrays.equals(new short[] { 2, 4 }, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new short[] { 1, 2, 3, 4, 5, 6, 7 }, 1, 3, 5);
+ assertTrue(Arrays.equals(new short[] { 1, 3, 5, 7 }, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeAll(new short[] { 1, 2, 3, 4, 5, 6, 7 }, 0, 2, 4, 6);
+ assertTrue(Arrays.equals(new short[] { 2, 4, 6 }, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ }
+
+ @Test
+ public void testRemoveAllShortArrayRemoveNone() {
+ short[] array1 = new short[] { 1, 2 };
+ short[] array2 = ArrayUtils.removeAll(array1);
+ assertNotSame(array1, array2);
+ assertArrayEquals(array1, array2);
+ assertEquals(short.class, array2.getClass().getComponentType());
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllShortArrayNegativeIndex() {
+ ArrayUtils.removeAll(new short[] { 1, 2 }, -1, 0);
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllShortArrayOutOfBoundsIndex() {
+ ArrayUtils.removeAll(new short[] { 1, 2 }, 2, 0);
+ }
+
+ @Test(expected = IndexOutOfBoundsException.class)
+ public void testRemoveAllNullShortArray() {
+ ArrayUtils.removeAll((short[]) null, 0);
+ }
+
+ @Test
+ public void testRemoveElementsObjectArray() {
+ Object[] array;
+ array = ArrayUtils.removeElements((Object[]) null, "a");
+ assertNull(array);
+ array = ArrayUtils.removeElements(ArrayUtils.EMPTY_OBJECT_ARRAY, "a");
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_OBJECT_ARRAY, array));
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new Object[] { "a" }, "a");
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_OBJECT_ARRAY, array));
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new Object[] { "a", "b" }, "a");
+ assertTrue(Arrays.equals(new Object[] { "b" }, array));
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new Object[] { "a", "b", "a" }, "a");
+ assertTrue(Arrays.equals(new Object[] { "b", "a" }, array));
+ assertEquals(Object.class, array.getClass().getComponentType());
+
+ array = ArrayUtils.removeElements((Object[]) null, "a", "b");
+ assertNull(array);
+ array = ArrayUtils.removeElements(ArrayUtils.EMPTY_OBJECT_ARRAY, "a", "b");
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_OBJECT_ARRAY, array));
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new Object[] { "a" }, "a", "b");
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_OBJECT_ARRAY, array));
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new Object[] { "a", "b" }, "a", "c");
+ assertTrue(Arrays.equals(new Object[] { "b" }, array));
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new Object[] { "a", "b", "a" }, "a");
+ assertTrue(Arrays.equals(new Object[] { "b", "a" }, array));
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new Object[] { "a", "b", "a" }, "a", "b");
+ assertTrue(Arrays.equals(new Object[] { "a" }, array));
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new Object[] { "a", "b", "a" }, "a", "a");
+ assertTrue(Arrays.equals(new Object[] { "b" }, array));
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new Object[] { "a", "b", "a" }, "a", "a", "a", "a");
+ assertTrue(Arrays.equals(new Object[] { "b" }, array));
+ assertEquals(Object.class, array.getClass().getComponentType());
+ }
+
+ @Test
+ public void testRemoveElementBooleanArray() {
+ boolean[] array;
+ array = ArrayUtils.removeElements((boolean[]) null, true);
+ assertNull(array);
+ array = ArrayUtils.removeElements(ArrayUtils.EMPTY_BOOLEAN_ARRAY, true);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new boolean[] { true }, true);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new boolean[] { true, false }, true);
+ assertTrue(Arrays.equals(new boolean[] { false }, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new boolean[] { true, false, true }, true);
+ assertTrue(Arrays.equals(new boolean[] { false, true }, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+
+ array = ArrayUtils.removeElements((boolean[]) null, true, false);
+ assertNull(array);
+ array = ArrayUtils.removeElements(ArrayUtils.EMPTY_BOOLEAN_ARRAY, true, false);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new boolean[] { true }, true, false);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new boolean[] { true, false }, true, false);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new boolean[] { true, false }, true, true);
+ assertTrue(Arrays.equals(new boolean[] { false }, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new boolean[] { true, false, true }, true, false);
+ assertTrue(Arrays.equals(new boolean[] { true }, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new boolean[] { true, false, true }, true, true);
+ assertTrue(Arrays.equals(new boolean[] { false }, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new boolean[] { true, false, true }, true, true, true, true);
+ assertTrue(Arrays.equals(new boolean[] { false }, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ }
+
+ @Test
+ public void testRemoveElementByteArray() {
+ byte[] array;
+ array = ArrayUtils.removeElements((byte[]) null, (byte) 1);
+ assertNull(array);
+ array = ArrayUtils.removeElements(ArrayUtils.EMPTY_BYTE_ARRAY, (byte) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_BYTE_ARRAY, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new byte[] { 1 }, (byte) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_BYTE_ARRAY, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new byte[] { 1, 2 }, (byte) 1);
+ assertTrue(Arrays.equals(new byte[] { 2 }, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new byte[] { 1, 2, 1 }, (byte) 1);
+ assertTrue(Arrays.equals(new byte[] { 2, 1 }, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+
+ array = ArrayUtils.removeElements((byte[]) null, (byte) 1, (byte) 2);
+ assertNull(array);
+ array = ArrayUtils.removeElements(ArrayUtils.EMPTY_BYTE_ARRAY, (byte) 1, (byte) 2);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_BYTE_ARRAY, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new byte[] { 1 }, (byte) 1, (byte) 2);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_BYTE_ARRAY, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new byte[] { 1, 2 }, (byte) 1, (byte) 2);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_BYTE_ARRAY, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new byte[] { 1, 2 }, (byte) 1, (byte) 1);
+ assertTrue(Arrays.equals(new byte[] { 2 }, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new byte[] { 1, 2, 1 }, (byte) 1, (byte) 2);
+ assertTrue(Arrays.equals(new byte[] { 1 }, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new byte[] { 1, 2, 1 }, (byte) 1, (byte) 1);
+ assertTrue(Arrays.equals(new byte[] { 2 }, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new byte[] { 1, 2, 1 }, (byte) 1, (byte) 1, (byte) 1, (byte) 1);
+ assertTrue(Arrays.equals(new byte[] { 2 }, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ }
+
+ @Test
+ public void testRemoveElementCharArray() {
+ char[] array;
+ array = ArrayUtils.removeElements((char[]) null, 'a');
+ assertNull(array);
+ array = ArrayUtils.removeElements(ArrayUtils.EMPTY_CHAR_ARRAY, 'a');
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_CHAR_ARRAY, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new char[] { 'a' }, 'a');
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_CHAR_ARRAY, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new char[] { 'a', 'b' }, 'a');
+ assertTrue(Arrays.equals(new char[] { 'b' }, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new char[] { 'a', 'b', 'a' }, 'a');
+ assertTrue(Arrays.equals(new char[] { 'b', 'a' }, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+
+ array = ArrayUtils.removeElements((char[]) null, 'a', 'b');
+ assertNull(array);
+ array = ArrayUtils.removeElements(ArrayUtils.EMPTY_CHAR_ARRAY, 'a', 'b');
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_CHAR_ARRAY, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new char[] { 'a' }, 'a', 'b');
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_CHAR_ARRAY, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new char[] { 'a', 'b' }, 'a', 'b');
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_CHAR_ARRAY, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new char[] { 'a', 'b' }, 'a', 'a');
+ assertTrue(Arrays.equals(new char[] { 'b' }, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new char[] { 'a', 'b', 'a' }, 'a', 'b');
+ assertTrue(Arrays.equals(new char[] { 'a' }, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new char[] { 'a', 'b', 'a' }, 'a', 'a');
+ assertTrue(Arrays.equals(new char[] { 'b' }, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new char[] { 'a', 'b', 'a' }, 'a', 'a', 'a', 'a');
+ assertTrue(Arrays.equals(new char[] { 'b' }, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ }
+
+ @Test
+ @SuppressWarnings("cast")
+ public void testRemoveElementDoubleArray() {
+ double[] array;
+ array = ArrayUtils.removeElements((double[]) null, (double) 1);
+ assertNull(array);
+ array = ArrayUtils.removeElements(ArrayUtils.EMPTY_DOUBLE_ARRAY, (double) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_DOUBLE_ARRAY, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new double[] { 1 }, (double) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_DOUBLE_ARRAY, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new double[] { 1, 2 }, (double) 1);
+ assertTrue(Arrays.equals(new double[] { 2 }, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new double[] { 1, 2, 1 }, (double) 1);
+ assertTrue(Arrays.equals(new double[] { 2, 1 }, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+
+ array = ArrayUtils.removeElements((double[]) null, (double) 1, (double) 2);
+ assertNull(array);
+ array = ArrayUtils.removeElements(ArrayUtils.EMPTY_DOUBLE_ARRAY, (double) 1, (double) 2);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_DOUBLE_ARRAY, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new double[] { 1 }, (double) 1, (double) 2);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_DOUBLE_ARRAY, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new double[] { 1, 2 }, (double) 1, (double) 2);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_DOUBLE_ARRAY, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new double[] { 1, 2 }, (double) 1, (double) 1);
+ assertTrue(Arrays.equals(new double[] { 2 }, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new double[] { 1, 2, 1 }, (double) 1, (double) 2);
+ assertTrue(Arrays.equals(new double[] { 1 }, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new double[] { 1, 2, 1 }, (double) 1, (double) 1);
+ assertTrue(Arrays.equals(new double[] { 2 }, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new double[] { 1, 2, 1 }, (double) 1, (double) 1, (double) 1, (double) 1);
+ assertTrue(Arrays.equals(new double[] { 2 }, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ }
+
+ @Test
+ @SuppressWarnings("cast")
+ public void testRemoveElementFloatArray() {
+ float[] array;
+ array = ArrayUtils.removeElements((float[]) null, (float) 1);
+ assertNull(array);
+ array = ArrayUtils.removeElements(ArrayUtils.EMPTY_FLOAT_ARRAY, (float) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_FLOAT_ARRAY, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new float[] { 1 }, (float) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_FLOAT_ARRAY, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new float[] { 1, 2 }, (float) 1);
+ assertTrue(Arrays.equals(new float[] { 2 }, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new float[] { 1, 2, 1 }, (float) 1);
+ assertTrue(Arrays.equals(new float[] { 2, 1 }, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+
+ array = ArrayUtils.removeElements((float[]) null, (float) 1, (float) 1);
+ assertNull(array);
+ array = ArrayUtils.removeElements(ArrayUtils.EMPTY_FLOAT_ARRAY, (float) 1, (float) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_FLOAT_ARRAY, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new float[] { 1 }, (float) 1, (float) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_FLOAT_ARRAY, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new float[] { 1, 2 }, (float) 1, (float) 2);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_FLOAT_ARRAY, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new float[] { 1, 2 }, (float) 1, (float) 1);
+ assertTrue(Arrays.equals(new float[] { 2 }, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new float[] { 1, 2, 1 }, (float) 1, (float) 1);
+ assertTrue(Arrays.equals(new float[] { 2 }, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new float[] { 1, 2, 1 }, (float) 1, (float) 2);
+ assertTrue(Arrays.equals(new float[] { 1 }, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new float[] { 1, 2, 1 }, (float) 1, (float) 1, (float) 1, (float) 1);
+ assertTrue(Arrays.equals(new float[] { 2 }, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ }
+
+ @Test
+ public void testRemoveElementIntArray() {
+ int[] array;
+ array = ArrayUtils.removeElements((int[]) null, 1);
+ assertNull(array);
+ array = ArrayUtils.removeElements(ArrayUtils.EMPTY_INT_ARRAY, 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_INT_ARRAY, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new int[] { 1 }, 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_INT_ARRAY, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new int[] { 1, 2 }, 1);
+ assertTrue(Arrays.equals(new int[] { 2 }, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new int[] { 1, 2, 1 }, 1);
+ assertTrue(Arrays.equals(new int[] { 2, 1 }, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+
+ array = ArrayUtils.removeElements((int[]) null, 1);
+ assertNull(array);
+ array = ArrayUtils.removeElements(ArrayUtils.EMPTY_INT_ARRAY, 1, 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_INT_ARRAY, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new int[] { 1 }, 1, 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_INT_ARRAY, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new int[] { 1, 2 }, 1, 2);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_INT_ARRAY, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new int[] { 1, 2 }, 1, 1);
+ assertTrue(Arrays.equals(new int[] { 2 }, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new int[] { 1, 2, 1 }, 1, 2);
+ assertTrue(Arrays.equals(new int[] { 1 }, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new int[] { 1, 2, 1 }, 1, 1);
+ assertTrue(Arrays.equals(new int[] { 2 }, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new int[] { 1, 2, 1 }, 1, 1, 1, 1);
+ assertTrue(Arrays.equals(new int[] { 2 }, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ }
+
+ @Test
+ @SuppressWarnings("cast")
+ public void testRemoveElementLongArray() {
+ long[] array;
+ array = ArrayUtils.removeElements((long[]) null, (long) 1);
+ assertNull(array);
+ array = ArrayUtils.removeElements(ArrayUtils.EMPTY_LONG_ARRAY, (long) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_LONG_ARRAY, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new long[] { 1 }, (long) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_LONG_ARRAY, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new long[] { 1, 2 }, (long) 1);
+ assertTrue(Arrays.equals(new long[] { 2 }, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new long[] { 1, 2, 1 }, (long) 1);
+ assertTrue(Arrays.equals(new long[] { 2, 1 }, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+
+ array = ArrayUtils.removeElements((long[]) null, (long) 1, (long) 1);
+ assertNull(array);
+ array = ArrayUtils.removeElements(ArrayUtils.EMPTY_LONG_ARRAY, (long) 1, (long) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_LONG_ARRAY, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new long[] { 1 }, (long) 1, (long) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_LONG_ARRAY, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new long[] { 1, 2 }, (long) 1, (long) 2);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_LONG_ARRAY, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new long[] { 1, 2 }, (long) 1, (long) 1);
+ assertTrue(Arrays.equals(new long[] { 2 }, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new long[] { 1, 2, 1 }, (long) 1, (long) 1);
+ assertTrue(Arrays.equals(new long[] { 2 }, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new long[] { 1, 2, 1 }, (long) 1, (long) 2);
+ assertTrue(Arrays.equals(new long[] { 1 }, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new long[] { 1, 2, 1 }, (long) 1, (long) 1, (long) 1, (long) 1);
+ assertTrue(Arrays.equals(new long[] { 2 }, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ }
+
+ @Test
+ public void testRemoveElementShortArray() {
+ short[] array;
+ array = ArrayUtils.removeElements((short[]) null, (short) 1);
+ assertNull(array);
+ array = ArrayUtils.removeElements(ArrayUtils.EMPTY_SHORT_ARRAY, (short) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_SHORT_ARRAY, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new short[] { 1 }, (short) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_SHORT_ARRAY, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new short[] { 1, 2 }, (short) 1);
+ assertTrue(Arrays.equals(new short[] { 2 }, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new short[] { 1, 2, 1 }, (short) 1);
+ assertTrue(Arrays.equals(new short[] { 2, 1 }, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+
+ array = ArrayUtils.removeElements((short[]) null, (short) 1, (short) 1);
+ assertNull(array);
+ array = ArrayUtils.removeElements(ArrayUtils.EMPTY_SHORT_ARRAY, (short) 1, (short) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_SHORT_ARRAY, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new short[] { 1 }, (short) 1, (short) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_SHORT_ARRAY, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new short[] { 1, 2 }, (short) 1, (short) 2);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_SHORT_ARRAY, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new short[] { 1, 2 }, (short) 1, (short) 1);
+ assertTrue(Arrays.equals(new short[] { 2 }, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new short[] { 1, 2, 1 }, (short) 1, (short) 1);
+ assertTrue(Arrays.equals(new short[] { 2 }, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new short[] { 1, 2, 1 }, (short) 1, (short) 2);
+ assertTrue(Arrays.equals(new short[] { 1 }, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElements(new short[] { 1, 2, 1 }, (short) 1, (short) 1, (short) 1, (short) 1);
+ assertTrue(Arrays.equals(new short[] { 2 }, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ }
+
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/ArrayUtilsRemoveTest.java b/ApacheCommonsLang/org/apache/commons/lang3/ArrayUtilsRemoveTest.java
new file mode 100644
index 0000000..5300878
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/ArrayUtilsRemoveTest.java
@@ -0,0 +1,487 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+package org.apache.commons.lang3;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.util.Arrays;
+
+import org.junit.Test;
+
+/**
+ * Tests ArrayUtils remove and removeElement methods.
+ *
+ * @version $Id: ArrayUtilsRemoveTest.java 1158284 2011-08-16 14:11:31Z ggregory $
+ */
+public class ArrayUtilsRemoveTest {
+
+ @Test
+ public void testRemoveObjectArray() {
+ Object[] array;
+ array = ArrayUtils.remove(new Object[] {"a"}, 0);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_OBJECT_ARRAY, array));
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new Object[] {"a", "b"}, 0);
+ assertTrue(Arrays.equals(new Object[] {"b"}, array));
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new Object[] {"a", "b"}, 1);
+ assertTrue(Arrays.equals(new Object[] {"a"}, array));
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new Object[] {"a", "b", "c"}, 1);
+ assertTrue(Arrays.equals(new Object[] {"a", "c"}, array));
+ assertEquals(Object.class, array.getClass().getComponentType());
+ try {
+ ArrayUtils.remove(new Object[] {"a", "b"}, -1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ try {
+ ArrayUtils.remove(new Object[] {"a", "b"}, 2);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ try {
+ ArrayUtils.remove((Object[]) null, 0);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ }
+
+ @Test
+ public void testRemoveNumberArray(){
+ Number[] inarray = {Integer.valueOf(1),Long.valueOf(2),Byte.valueOf((byte) 3)};
+ assertEquals(3, inarray.length);
+ Number[] outarray;
+ outarray = ArrayUtils.remove(inarray, 1);
+ assertEquals(2, outarray.length);
+ assertEquals(Number.class, outarray.getClass().getComponentType());
+ outarray = ArrayUtils.remove(outarray, 1);
+ assertEquals(1, outarray.length);
+ assertEquals(Number.class, outarray.getClass().getComponentType());
+ outarray = ArrayUtils.remove(outarray, 0);
+ assertEquals(0, outarray.length);
+ assertEquals(Number.class, outarray.getClass().getComponentType());
+ }
+
+ @Test
+ public void testRemoveBooleanArray() {
+ boolean[] array;
+ array = ArrayUtils.remove(new boolean[] {true}, 0);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new boolean[] {true, false}, 0);
+ assertTrue(Arrays.equals(new boolean[] {false}, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new boolean[] {true, false}, 1);
+ assertTrue(Arrays.equals(new boolean[] {true}, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new boolean[] {true, false, true}, 1);
+ assertTrue(Arrays.equals(new boolean[] {true, true}, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ try {
+ ArrayUtils.remove(new boolean[] {true, false}, -1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ try {
+ ArrayUtils.remove(new boolean[] {true, false}, 2);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ try {
+ ArrayUtils.remove((boolean[]) null, 0);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ }
+
+ @Test
+ public void testRemoveByteArray() {
+ byte[] array;
+ array = ArrayUtils.remove(new byte[] {1}, 0);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_BYTE_ARRAY, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new byte[] {1, 2}, 0);
+ assertTrue(Arrays.equals(new byte[] {2}, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new byte[] {1, 2}, 1);
+ assertTrue(Arrays.equals(new byte[] {1}, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new byte[] {1, 2, 1}, 1);
+ assertTrue(Arrays.equals(new byte[] {1, 1}, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ try {
+ ArrayUtils.remove(new byte[] {1, 2}, -1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ try {
+ ArrayUtils.remove(new byte[] {1, 2}, 2);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ try {
+ ArrayUtils.remove((byte[]) null, 0);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ }
+
+ @Test
+ public void testRemoveCharArray() {
+ char[] array;
+ array = ArrayUtils.remove(new char[] {'a'}, 0);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_CHAR_ARRAY, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new char[] {'a', 'b'}, 0);
+ assertTrue(Arrays.equals(new char[] {'b'}, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new char[] {'a', 'b'}, 1);
+ assertTrue(Arrays.equals(new char[] {'a'}, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new char[] {'a', 'b', 'c'}, 1);
+ assertTrue(Arrays.equals(new char[] {'a', 'c'}, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ try {
+ ArrayUtils.remove(new char[] {'a', 'b'}, -1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ try {
+ ArrayUtils.remove(new char[] {'a', 'b'}, 2);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ try {
+ ArrayUtils.remove((char[]) null, 0);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ }
+
+ @Test
+ public void testRemoveDoubleArray() {
+ double[] array;
+ array = ArrayUtils.remove(new double[] {1}, 0);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_DOUBLE_ARRAY, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new double[] {1, 2}, 0);
+ assertTrue(Arrays.equals(new double[] {2}, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new double[] {1, 2}, 1);
+ assertTrue(Arrays.equals(new double[] {1}, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new double[] {1, 2, 1}, 1);
+ assertTrue(Arrays.equals(new double[] {1, 1}, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ try {
+ ArrayUtils.remove(new double[] {1, 2}, -1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ try {
+ ArrayUtils.remove(new double[] {1, 2}, 2);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ try {
+ ArrayUtils.remove((double[]) null, 0);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ }
+
+ @Test
+ public void testRemoveFloatArray() {
+ float[] array;
+ array = ArrayUtils.remove(new float[] {1}, 0);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_FLOAT_ARRAY, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new float[] {1, 2}, 0);
+ assertTrue(Arrays.equals(new float[] {2}, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new float[] {1, 2}, 1);
+ assertTrue(Arrays.equals(new float[] {1}, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new float[] {1, 2, 1}, 1);
+ assertTrue(Arrays.equals(new float[] {1, 1}, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ try {
+ ArrayUtils.remove(new float[] {1, 2}, -1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ try {
+ ArrayUtils.remove(new float[] {1, 2}, 2);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ try {
+ ArrayUtils.remove((float[]) null, 0);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ }
+
+ @Test
+ public void testRemoveIntArray() {
+ int[] array;
+ array = ArrayUtils.remove(new int[] {1}, 0);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_INT_ARRAY, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new int[] {1, 2}, 0);
+ assertTrue(Arrays.equals(new int[] {2}, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new int[] {1, 2}, 1);
+ assertTrue(Arrays.equals(new int[] {1}, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new int[] {1, 2, 1}, 1);
+ assertTrue(Arrays.equals(new int[] {1, 1}, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ try {
+ ArrayUtils.remove(new int[] {1, 2}, -1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ try {
+ ArrayUtils.remove(new int[] {1, 2}, 2);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ try {
+ ArrayUtils.remove((int[]) null, 0);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ }
+
+ @Test
+ public void testRemoveLongArray() {
+ long[] array;
+ array = ArrayUtils.remove(new long[] {1}, 0);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_LONG_ARRAY, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new long[] {1, 2}, 0);
+ assertTrue(Arrays.equals(new long[] {2}, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new long[] {1, 2}, 1);
+ assertTrue(Arrays.equals(new long[] {1}, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new long[] {1, 2, 1}, 1);
+ assertTrue(Arrays.equals(new long[] {1, 1}, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ try {
+ ArrayUtils.remove(new long[] {1, 2}, -1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ try {
+ ArrayUtils.remove(new long[] {1, 2}, 2);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ try {
+ ArrayUtils.remove((long[]) null, 0);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ }
+
+ @Test
+ public void testRemoveShortArray() {
+ short[] array;
+ array = ArrayUtils.remove(new short[] {1}, 0);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_SHORT_ARRAY, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new short[] {1, 2}, 0);
+ assertTrue(Arrays.equals(new short[] {2}, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new short[] {1, 2}, 1);
+ assertTrue(Arrays.equals(new short[] {1}, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.remove(new short[] {1, 2, 1}, 1);
+ assertTrue(Arrays.equals(new short[] {1, 1}, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ try {
+ ArrayUtils.remove(new short[] {1, 2}, -1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ try {
+ ArrayUtils.remove(new short[] {1, 2}, 2);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ try {
+ ArrayUtils.remove((short[]) null, 0);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {}
+ }
+
+ @Test
+ public void testRemoveElementObjectArray() {
+ Object[] array;
+ array = ArrayUtils.removeElement((Object[]) null, "a");
+ assertNull(array);
+ array = ArrayUtils.removeElement(ArrayUtils.EMPTY_OBJECT_ARRAY, "a");
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_OBJECT_ARRAY, array));
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new Object[] {"a"}, "a");
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_OBJECT_ARRAY, array));
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new Object[] {"a", "b"}, "a");
+ assertTrue(Arrays.equals(new Object[] {"b"}, array));
+ assertEquals(Object.class, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new Object[] {"a", "b", "a"}, "a");
+ assertTrue(Arrays.equals(new Object[] {"b", "a"}, array));
+ assertEquals(Object.class, array.getClass().getComponentType());
+ }
+
+ @Test
+ public void testRemoveElementBooleanArray() {
+ boolean[] array;
+ array = ArrayUtils.removeElement((boolean[]) null, true);
+ assertNull(array);
+ array = ArrayUtils.removeElement(ArrayUtils.EMPTY_BOOLEAN_ARRAY, true);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new boolean[] {true}, true);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new boolean[] {true, false}, true);
+ assertTrue(Arrays.equals(new boolean[] {false}, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new boolean[] {true, false, true}, true);
+ assertTrue(Arrays.equals(new boolean[] {false, true}, array));
+ assertEquals(Boolean.TYPE, array.getClass().getComponentType());
+ }
+
+ @Test
+ public void testRemoveElementByteArray() {
+ byte[] array;
+ array = ArrayUtils.removeElement((byte[]) null, (byte) 1);
+ assertNull(array);
+ array = ArrayUtils.removeElement(ArrayUtils.EMPTY_BYTE_ARRAY, (byte) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_BYTE_ARRAY, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new byte[] {1}, (byte) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_BYTE_ARRAY, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new byte[] {1, 2}, (byte) 1);
+ assertTrue(Arrays.equals(new byte[] {2}, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new byte[] {1, 2, 1}, (byte) 1);
+ assertTrue(Arrays.equals(new byte[] {2, 1}, array));
+ assertEquals(Byte.TYPE, array.getClass().getComponentType());
+ }
+
+ @Test
+ public void testRemoveElementCharArray() {
+ char[] array;
+ array = ArrayUtils.removeElement((char[]) null, 'a');
+ assertNull(array);
+ array = ArrayUtils.removeElement(ArrayUtils.EMPTY_CHAR_ARRAY, 'a');
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_CHAR_ARRAY, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new char[] {'a'}, 'a');
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_CHAR_ARRAY, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new char[] {'a', 'b'}, 'a');
+ assertTrue(Arrays.equals(new char[] {'b'}, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new char[] {'a', 'b', 'a'}, 'a');
+ assertTrue(Arrays.equals(new char[] {'b', 'a'}, array));
+ assertEquals(Character.TYPE, array.getClass().getComponentType());
+ }
+
+ @Test
+ @SuppressWarnings("cast")
+ public void testRemoveElementDoubleArray() {
+ double[] array;
+ array = ArrayUtils.removeElement((double[]) null, (double) 1);
+ assertNull(array);
+ array = ArrayUtils.removeElement(ArrayUtils.EMPTY_DOUBLE_ARRAY, (double) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_DOUBLE_ARRAY, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new double[] {1}, (double) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_DOUBLE_ARRAY, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new double[] {1, 2}, (double) 1);
+ assertTrue(Arrays.equals(new double[] {2}, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new double[] {1, 2, 1}, (double) 1);
+ assertTrue(Arrays.equals(new double[] {2, 1}, array));
+ assertEquals(Double.TYPE, array.getClass().getComponentType());
+ }
+
+ @Test
+ @SuppressWarnings("cast")
+ public void testRemoveElementFloatArray() {
+ float[] array;
+ array = ArrayUtils.removeElement((float[]) null, (float) 1);
+ assertNull(array);
+ array = ArrayUtils.removeElement(ArrayUtils.EMPTY_FLOAT_ARRAY, (float) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_FLOAT_ARRAY, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new float[] {1}, (float) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_FLOAT_ARRAY, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new float[] {1, 2}, (float) 1);
+ assertTrue(Arrays.equals(new float[] {2}, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new float[] {1, 2, 1}, (float) 1);
+ assertTrue(Arrays.equals(new float[] {2, 1}, array));
+ assertEquals(Float.TYPE, array.getClass().getComponentType());
+ }
+
+ @Test
+ public void testRemoveElementIntArray() {
+ int[] array;
+ array = ArrayUtils.removeElement((int[]) null, 1);
+ assertNull(array);
+ array = ArrayUtils.removeElement(ArrayUtils.EMPTY_INT_ARRAY, 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_INT_ARRAY, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new int[] {1}, 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_INT_ARRAY, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new int[] {1, 2}, 1);
+ assertTrue(Arrays.equals(new int[] {2}, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new int[] {1, 2, 1}, 1);
+ assertTrue(Arrays.equals(new int[] {2, 1}, array));
+ assertEquals(Integer.TYPE, array.getClass().getComponentType());
+ }
+
+ @Test
+ @SuppressWarnings("cast")
+ public void testRemoveElementLongArray() {
+ long[] array;
+ array = ArrayUtils.removeElement((long[]) null, (long) 1);
+ assertNull(array);
+ array = ArrayUtils.removeElement(ArrayUtils.EMPTY_LONG_ARRAY, (long) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_LONG_ARRAY, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new long[] {1}, (long) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_LONG_ARRAY, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new long[] {1, 2}, (long) 1);
+ assertTrue(Arrays.equals(new long[] {2}, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new long[] {1, 2, 1}, (long) 1);
+ assertTrue(Arrays.equals(new long[] {2, 1}, array));
+ assertEquals(Long.TYPE, array.getClass().getComponentType());
+ }
+
+ @Test
+ public void testRemoveElementShortArray() {
+ short[] array;
+ array = ArrayUtils.removeElement((short[]) null, (short) 1);
+ assertNull(array);
+ array = ArrayUtils.removeElement(ArrayUtils.EMPTY_SHORT_ARRAY, (short) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_SHORT_ARRAY, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new short[] {1}, (short) 1);
+ assertTrue(Arrays.equals(ArrayUtils.EMPTY_SHORT_ARRAY, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new short[] {1, 2}, (short) 1);
+ assertTrue(Arrays.equals(new short[] {2}, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ array = ArrayUtils.removeElement(new short[] {1, 2, 1}, (short) 1);
+ assertTrue(Arrays.equals(new short[] {2, 1}, array));
+ assertEquals(Short.TYPE, array.getClass().getComponentType());
+ }
+
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/ArrayUtilsTest.java b/ApacheCommonsLang/org/apache/commons/lang3/ArrayUtilsTest.java
new file mode 100644
index 0000000..3eb1691
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/ArrayUtilsTest.java
@@ -0,0 +1,2922 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+package org.apache.commons.lang3;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Modifier;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.Map;
+
+import junit.framework.TestCase;
+
+/**
+ * Unit tests {@link org.apache.commons.lang3.ArrayUtils}.
+ *
+ * @version $Id: ArrayUtilsTest.java 1309977 2012-04-05 17:53:39Z ggregory $
+ */
+public class ArrayUtilsTest extends TestCase {
+
+ public ArrayUtilsTest(String name) {
+ super(name);
+ }
+
+ //-----------------------------------------------------------------------
+ public void testConstructor() {
+ assertNotNull(new ArrayUtils());
+ Constructor>[] cons = ArrayUtils.class.getDeclaredConstructors();
+ assertEquals(1, cons.length);
+ assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
+ assertEquals(true, Modifier.isPublic(ArrayUtils.class.getModifiers()));
+ assertEquals(false, Modifier.isFinal(ArrayUtils.class.getModifiers()));
+ }
+
+ //-----------------------------------------------------------------------
+ public void testToString() {
+ assertEquals("{}", ArrayUtils.toString(null));
+ assertEquals("{}", ArrayUtils.toString(new Object[0]));
+ assertEquals("{}", ArrayUtils.toString(new String[0]));
+ assertEquals("{}", ArrayUtils.toString(new String[] {null}));
+ assertEquals("{pink,blue}", ArrayUtils.toString(new String[] {"pink","blue"}));
+
+ assertEquals("", ArrayUtils.toString(null, ""));
+ assertEquals("{}", ArrayUtils.toString(new Object[0], ""));
+ assertEquals("{}", ArrayUtils.toString(new String[0], ""));
+ assertEquals("{}", ArrayUtils.toString(new String[] {null}, ""));
+ assertEquals("{pink,blue}", ArrayUtils.toString(new String[] {"pink","blue"}, ""));
+ }
+
+ //-----------------------------------------------------------------------
+ public void testHashCode() {
+ long[][] array1 = new long[][] {{2,5}, {4,5}};
+ long[][] array2 = new long[][] {{2,5}, {4,6}};
+ assertEquals(true, ArrayUtils.hashCode(array1) == ArrayUtils.hashCode(array1));
+ assertEquals(false, ArrayUtils.hashCode(array1) == ArrayUtils.hashCode(array2));
+
+ Object[] array3 = new Object[] {new String(new char[] {'A', 'B'})};
+ Object[] array4 = new Object[] {"AB"};
+ assertEquals(true, ArrayUtils.hashCode(array3) == ArrayUtils.hashCode(array3));
+ assertEquals(true, ArrayUtils.hashCode(array3) == ArrayUtils.hashCode(array4));
+
+ Object[] arrayA = new Object[] {new boolean[] {true, false}, new int[] {6, 7}};
+ Object[] arrayB = new Object[] {new boolean[] {true, false}, new int[] {6, 7}};
+ assertEquals(true, ArrayUtils.hashCode(arrayB) == ArrayUtils.hashCode(arrayA));
+ }
+
+ //-----------------------------------------------------------------------
+ private void assertIsEquals(Object array1, Object array2, Object array3) {
+ assertEquals(true, ArrayUtils.isEquals(array1, array1));
+ assertEquals(true, ArrayUtils.isEquals(array2, array2));
+ assertEquals(true, ArrayUtils.isEquals(array3, array3));
+ assertEquals(false, ArrayUtils.isEquals(array1, array2));
+ assertEquals(false, ArrayUtils.isEquals(array2, array1));
+ assertEquals(false, ArrayUtils.isEquals(array1, array3));
+ assertEquals(false, ArrayUtils.isEquals(array3, array1));
+ assertEquals(false, ArrayUtils.isEquals(array1, array2));
+ assertEquals(false, ArrayUtils.isEquals(array2, array1));
+ }
+
+ public void testIsEquals() {
+ long[][] larray1 = new long[][]{{2, 5}, {4, 5}};
+ long[][] larray2 = new long[][]{{2, 5}, {4, 6}};
+ long[] larray3 = new long[]{2, 5};
+ this.assertIsEquals(larray1, larray2, larray3);
+
+ int[][] iarray1 = new int[][]{{2, 5}, {4, 5}};
+ int[][] iarray2 = new int[][]{{2, 5}, {4, 6}};
+ int[] iarray3 = new int[]{2, 5};
+ this.assertIsEquals(iarray1, iarray2, iarray3);
+
+ short[][] sarray1 = new short[][]{{2, 5}, {4, 5}};
+ short[][] sarray2 = new short[][]{{2, 5}, {4, 6}};
+ short[] sarray3 = new short[]{2, 5};
+ this.assertIsEquals(sarray1, sarray2, sarray3);
+
+ float[][] farray1 = new float[][]{{2, 5}, {4, 5}};
+ float[][] farray2 = new float[][]{{2, 5}, {4, 6}};
+ float[] farray3 = new float[]{2, 5};
+ this.assertIsEquals(farray1, farray2, farray3);
+
+ double[][] darray1 = new double[][]{{2, 5}, {4, 5}};
+ double[][] darray2 = new double[][]{{2, 5}, {4, 6}};
+ double[] darray3 = new double[]{2, 5};
+ this.assertIsEquals(darray1, darray2, darray3);
+
+ byte[][] byteArray1 = new byte[][]{{2, 5}, {4, 5}};
+ byte[][] byteArray2 = new byte[][]{{2, 5}, {4, 6}};
+ byte[] byteArray3 = new byte[]{2, 5};
+ this.assertIsEquals(byteArray1, byteArray2, byteArray3);
+
+ char[][] charArray1 = new char[][]{{2, 5}, {4, 5}};
+ char[][] charArray2 = new char[][]{{2, 5}, {4, 6}};
+ char[] charArray3 = new char[]{2, 5};
+ this.assertIsEquals(charArray1, charArray2, charArray3);
+
+ boolean[][] barray1 = new boolean[][]{{true, false}, {true, true}};
+ boolean[][] barray2 = new boolean[][]{{true, false}, {true, false}};
+ boolean[] barray3 = new boolean[]{false, true};
+ this.assertIsEquals(barray1, barray2, barray3);
+
+ Object[] array3 = new Object[]{new String(new char[]{'A', 'B'})};
+ Object[] array4 = new Object[]{"AB"};
+ assertEquals(true, ArrayUtils.isEquals(array3, array3));
+ assertEquals(true, ArrayUtils.isEquals(array3, array4));
+
+ assertEquals(true, ArrayUtils.isEquals(null, null));
+ assertEquals(false, ArrayUtils.isEquals(null, array4));
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Tests generic array creation with parameters of same type.
+ */
+ public void testArrayCreation()
+ {
+ final String[] array = ArrayUtils.toArray("foo", "bar");
+ assertEquals(2, array.length);
+ assertEquals("foo", array[0]);
+ assertEquals("bar", array[1]);
+ }
+
+ /**
+ * Tests generic array creation with general return type.
+ */
+ public void testArrayCreationWithGeneralReturnType()
+ {
+ final Object obj = ArrayUtils.toArray("foo", "bar");
+ assertTrue(obj instanceof String[]);
+ }
+
+ /**
+ * Tests generic array creation with parameters of common base type.
+ */
+ public void testArrayCreationWithDifferentTypes()
+ {
+ final Number[] array = ArrayUtils.toArray(Integer.valueOf(42), Double.valueOf(Math.PI));
+ assertEquals(2, array.length);
+ assertEquals(Integer.valueOf(42), array[0]);
+ assertEquals(Double.valueOf(Math.PI), array[1]);
+ }
+
+ /**
+ * Tests generic array creation with generic type.
+ */
+ public void testIndirectArrayCreation()
+ {
+ final String[] array = toArrayPropagatingType("foo", "bar");
+ assertEquals(2, array.length);
+ assertEquals("foo", array[0]);
+ assertEquals("bar", array[1]);
+ }
+
+ /**
+ * Tests generic empty array creation with generic type.
+ */
+ public void testEmptyArrayCreation()
+ {
+ final String[] array = ArrayUtils.toArray();
+ assertEquals(0, array.length);
+ }
+
+ /**
+ * Tests indirect generic empty array creation with generic type.
+ */
+ public void testIndirectEmptyArrayCreation()
+ {
+ final String[] array = ArrayUtilsTest.toArrayPropagatingType();
+ assertEquals(0, array.length);
+ }
+
+ private static T[] toArrayPropagatingType(final T... items)
+ {
+ return ArrayUtils.toArray(items);
+ }
+
+ //-----------------------------------------------------------------------
+ public void testToMap() {
+ Map, ?> map = ArrayUtils.toMap(new String[][] {{"foo", "bar"}, {"hello", "world"}});
+
+ assertEquals("bar", map.get("foo"));
+ assertEquals("world", map.get("hello"));
+
+ assertEquals(null, ArrayUtils.toMap(null));
+ try {
+ ArrayUtils.toMap(new String[][] {{"foo", "bar"}, {"short"}});
+ fail("exception expected");
+ } catch (IllegalArgumentException ex) {}
+ try {
+ ArrayUtils.toMap(new Object[] {new Object[] {"foo", "bar"}, "illegal type"});
+ fail("exception expected");
+ } catch (IllegalArgumentException ex) {}
+ try {
+ ArrayUtils.toMap(new Object[] {new Object[] {"foo", "bar"}, null});
+ fail("exception expected");
+ } catch (IllegalArgumentException ex) {}
+
+ map = ArrayUtils.toMap(new Object[] {new Map.Entry() {
+ @Override
+ public Object getKey() {
+ return "foo";
+ }
+ @Override
+ public Object getValue() {
+ return "bar";
+ }
+ @Override
+ public Object setValue(Object value) {
+ throw new UnsupportedOperationException();
+ }
+ @Override
+ public boolean equals(Object o) {
+ throw new UnsupportedOperationException();
+ }
+ @Override
+ public int hashCode() {
+ throw new UnsupportedOperationException();
+ }
+ }});
+ assertEquals("bar", map.get("foo"));
+ }
+
+ //-----------------------------------------------------------------------
+ public void testClone() {
+ assertEquals(null, ArrayUtils.clone((Object[]) null));
+ Object[] original1 = new Object[0];
+ Object[] cloned1 = ArrayUtils.clone(original1);
+ assertTrue(Arrays.equals(original1, cloned1));
+ assertTrue(original1 != cloned1);
+
+ StringBuffer buf = new StringBuffer("pick");
+ original1 = new Object[] {buf, "a", new String[] {"stick"}};
+ cloned1 = ArrayUtils.clone(original1);
+ assertTrue(Arrays.equals(original1, cloned1));
+ assertTrue(original1 != cloned1);
+ assertSame(original1[0], cloned1[0]);
+ assertSame(original1[1], cloned1[1]);
+ assertSame(original1[2], cloned1[2]);
+ }
+
+ public void testCloneBoolean() {
+ assertEquals(null, ArrayUtils.clone((boolean[]) null));
+ boolean[] original = new boolean[] {true, false};
+ boolean[] cloned = ArrayUtils.clone(original);
+ assertTrue(Arrays.equals(original, cloned));
+ assertTrue(original != cloned);
+ }
+
+ public void testCloneLong() {
+ assertEquals(null, ArrayUtils.clone((long[]) null));
+ long[] original = new long[] {0L, 1L};
+ long[] cloned = ArrayUtils.clone(original);
+ assertTrue(Arrays.equals(original, cloned));
+ assertTrue(original != cloned);
+ }
+
+ public void testCloneInt() {
+ assertEquals(null, ArrayUtils.clone((int[]) null));
+ int[] original = new int[] {5, 8};
+ int[] cloned = ArrayUtils.clone(original);
+ assertTrue(Arrays.equals(original, cloned));
+ assertTrue(original != cloned);
+ }
+
+ public void testCloneShort() {
+ assertEquals(null, ArrayUtils.clone((short[]) null));
+ short[] original = new short[] {1, 4};
+ short[] cloned = ArrayUtils.clone(original);
+ assertTrue(Arrays.equals(original, cloned));
+ assertTrue(original != cloned);
+ }
+
+ public void testCloneChar() {
+ assertEquals(null, ArrayUtils.clone((char[]) null));
+ char[] original = new char[] {'a', '4'};
+ char[] cloned = ArrayUtils.clone(original);
+ assertTrue(Arrays.equals(original, cloned));
+ assertTrue(original != cloned);
+ }
+
+ public void testCloneByte() {
+ assertEquals(null, ArrayUtils.clone((byte[]) null));
+ byte[] original = new byte[] {1, 6};
+ byte[] cloned = ArrayUtils.clone(original);
+ assertTrue(Arrays.equals(original, cloned));
+ assertTrue(original != cloned);
+ }
+
+ public void testCloneDouble() {
+ assertEquals(null, ArrayUtils.clone((double[]) null));
+ double[] original = new double[] {2.4d, 5.7d};
+ double[] cloned = ArrayUtils.clone(original);
+ assertTrue(Arrays.equals(original, cloned));
+ assertTrue(original != cloned);
+ }
+
+ public void testCloneFloat() {
+ assertEquals(null, ArrayUtils.clone((float[]) null));
+ float[] original = new float[] {2.6f, 6.4f};
+ float[] cloned = ArrayUtils.clone(original);
+ assertTrue(Arrays.equals(original, cloned));
+ assertTrue(original != cloned);
+ }
+
+ //-----------------------------------------------------------------------
+
+ public void testNullToEmptyBoolean() {
+ // Test null handling
+ assertEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.nullToEmpty((boolean[]) null));
+ // Test valid array handling
+ boolean[] original = new boolean[] {true, false};
+ assertEquals(original, ArrayUtils.nullToEmpty(original));
+ // Test empty array handling
+ boolean[] empty = new boolean[]{};
+ boolean[] result = ArrayUtils.nullToEmpty(empty);
+ assertEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, result);
+ assertTrue(empty != result);
+ }
+
+ public void testNullToEmptyLong() {
+ // Test null handling
+ assertEquals(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.nullToEmpty((long[]) null));
+ // Test valid array handling
+ long[] original = new long[] {1L, 2L};
+ assertEquals(original, ArrayUtils.nullToEmpty(original));
+ // Test empty array handling
+ long[] empty = new long[]{};
+ long[] result = ArrayUtils.nullToEmpty(empty);
+ assertEquals(ArrayUtils.EMPTY_LONG_ARRAY, result);
+ assertTrue(empty != result);
+ }
+
+ public void testNullToEmptyInt() {
+ // Test null handling
+ assertEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.nullToEmpty((int[]) null));
+ // Test valid array handling
+ int[] original = new int[] {1, 2};
+ assertEquals(original, ArrayUtils.nullToEmpty(original));
+ // Test empty array handling
+ int[] empty = new int[]{};
+ int[] result = ArrayUtils.nullToEmpty(empty);
+ assertEquals(ArrayUtils.EMPTY_INT_ARRAY, result);
+ assertTrue(empty != result);
+ }
+
+ public void testNullToEmptyShort() {
+ // Test null handling
+ assertEquals(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.nullToEmpty((short[]) null));
+ // Test valid array handling
+ short[] original = new short[] {1, 2};
+ assertEquals(original, ArrayUtils.nullToEmpty(original));
+ // Test empty array handling
+ short[] empty = new short[]{};
+ short[] result = ArrayUtils.nullToEmpty(empty);
+ assertEquals(ArrayUtils.EMPTY_SHORT_ARRAY, result);
+ assertTrue(empty != result);
+ }
+
+ public void testNullToEmptyChar() {
+ // Test null handling
+ assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.nullToEmpty((char[]) null));
+ // Test valid array handling
+ char[] original = new char[] {'a', 'b'};
+ assertEquals(original, ArrayUtils.nullToEmpty(original));
+ // Test empty array handling
+ char[] empty = new char[]{};
+ char[] result = ArrayUtils.nullToEmpty(empty);
+ assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, result);
+ assertTrue(empty != result);
+ }
+
+ public void testNullToEmptyByte() {
+ // Test null handling
+ assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.nullToEmpty((byte[]) null));
+ // Test valid array handling
+ byte[] original = new byte[] {0x0F, 0x0E};
+ assertEquals(original, ArrayUtils.nullToEmpty(original));
+ // Test empty array handling
+ byte[] empty = new byte[]{};
+ byte[] result = ArrayUtils.nullToEmpty(empty);
+ assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, result);
+ assertTrue(empty != result);
+ }
+
+ public void testNullToEmptyDouble() {
+ // Test null handling
+ assertEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.nullToEmpty((double[]) null));
+ // Test valid array handling
+ double[] original = new double[] {1L, 2L};
+ assertEquals(original, ArrayUtils.nullToEmpty(original));
+ // Test empty array handling
+ double[] empty = new double[]{};
+ double[] result = ArrayUtils.nullToEmpty(empty);
+ assertEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, result);
+ assertTrue(empty != result);
+ }
+
+ public void testNullToEmptyFloat() {
+ // Test null handling
+ assertEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.nullToEmpty((float[]) null));
+ // Test valid array handling
+ float[] original = new float[] {2.6f, 3.8f};
+ assertEquals(original, ArrayUtils.nullToEmpty(original));
+ // Test empty array handling
+ float[] empty = new float[]{};
+ float[] result = ArrayUtils.nullToEmpty(empty);
+ assertEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, result);
+ assertTrue(empty != result);
+ }
+
+ public void testNullToEmptyObject() {
+ // Test null handling
+ assertEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Object[]) null));
+ // Test valid array handling
+ Object[] original = new Object[] {Boolean.TRUE, Boolean.FALSE};
+ assertEquals(original, ArrayUtils.nullToEmpty(original));
+ // Test empty array handling
+ Object[] empty = new Object[]{};
+ Object[] result = ArrayUtils.nullToEmpty(empty);
+ assertEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, result);
+ assertTrue(empty != result);
+ }
+
+ public void testNullToEmptyString() {
+ // Test null handling
+ assertEquals(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.nullToEmpty((String[]) null));
+ // Test valid array handling
+ String[] original = new String[] {"abc", "def"};
+ assertEquals(original, ArrayUtils.nullToEmpty(original));
+ // Test empty array handling
+ String[] empty = new String[]{};
+ String[] result = ArrayUtils.nullToEmpty(empty);
+ assertEquals(ArrayUtils.EMPTY_STRING_ARRAY, result);
+ assertTrue(empty != result);
+ }
+
+ public void testNullToEmptyBooleanObject() {
+ // Test null handling
+ assertEquals(ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Boolean[]) null));
+ // Test valid array handling
+ Boolean[] original = new Boolean[] {Boolean.TRUE, Boolean.FALSE};
+ assertEquals(original, ArrayUtils.nullToEmpty(original));
+ // Test empty array handling
+ Boolean[] empty = new Boolean[]{};
+ Boolean[] result = ArrayUtils.nullToEmpty(empty);
+ assertEquals(ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY, result);
+ assertTrue(empty != result);
+ }
+
+ public void testNullToEmptyLongObject() {
+ // Test null handling
+ assertEquals(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Long[]) null));
+ // Test valid array handling
+ @SuppressWarnings("boxing")
+ Long[] original = new Long[] {1L, 2L};
+ assertEquals(original, ArrayUtils.nullToEmpty(original));
+ // Test empty array handling
+ Long[] empty = new Long[]{};
+ Long[] result = ArrayUtils.nullToEmpty(empty);
+ assertEquals(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY, result);
+ assertTrue(empty != result);
+ }
+
+ public void testNullToEmptyIntObject() {
+ // Test null handling
+ assertEquals(ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Integer[]) null));
+ // Test valid array handling
+ Integer[] original = new Integer[] {1, 2};
+ assertEquals(original, ArrayUtils.nullToEmpty(original));
+ // Test empty array handling
+ Integer[] empty = new Integer[]{};
+ Integer[] result = ArrayUtils.nullToEmpty(empty);
+ assertEquals(ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY, result);
+ assertTrue(empty != result);
+ }
+
+ public void testNullToEmptyShortObject() {
+ // Test null handling
+ assertEquals(ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Short[]) null));
+ // Test valid array handling
+ @SuppressWarnings("boxing")
+ Short[] original = new Short[] {1, 2};
+ assertEquals(original, ArrayUtils.nullToEmpty(original));
+ // Test empty array handling
+ Short[] empty = new Short[]{};
+ Short[] result = ArrayUtils.nullToEmpty(empty);
+ assertEquals(ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY, result);
+ assertTrue(empty != result);
+ }
+
+ public void testNullToEmptyCharObject() {
+ // Test null handling
+ assertEquals(ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Character[]) null));
+ // Test valid array handling
+ Character[] original = new Character[] {'a', 'b'};
+ assertEquals(original, ArrayUtils.nullToEmpty(original));
+ // Test empty array handling
+ Character[] empty = new Character[]{};
+ Character[] result = ArrayUtils.nullToEmpty(empty);
+ assertEquals(ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY, result);
+ assertTrue(empty != result);
+ }
+
+ public void testNullToEmptyByteObject() {
+ // Test null handling
+ assertEquals(ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Byte[]) null));
+ // Test valid array handling
+ Byte[] original = new Byte[] {0x0F, 0x0E};
+ assertEquals(original, ArrayUtils.nullToEmpty(original));
+ // Test empty array handling
+ Byte[] empty = new Byte[]{};
+ Byte[] result = ArrayUtils.nullToEmpty(empty);
+ assertEquals(ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY, result);
+ assertTrue(empty != result);
+ }
+
+ public void testNullToEmptyDoubleObject() {
+ // Test null handling
+ assertEquals(ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Double[]) null));
+ // Test valid array handling
+ Double[] original = new Double[] {1D, 2D};
+ assertEquals(original, ArrayUtils.nullToEmpty(original));
+ // Test empty array handling
+ Double[] empty = new Double[]{};
+ Double[] result = ArrayUtils.nullToEmpty(empty);
+ assertEquals(ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY, result);
+ assertTrue(empty != result);
+ }
+
+ public void testNullToEmptyFloatObject() {
+ // Test null handling
+ assertEquals(ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Float[]) null));
+ // Test valid array handling
+ Float[] original = new Float[] {2.6f, 3.8f};
+ assertEquals(original, ArrayUtils.nullToEmpty(original));
+ // Test empty array handling
+ Float[] empty = new Float[]{};
+ Float[] result = ArrayUtils.nullToEmpty(empty);
+ assertEquals(ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY, result);
+ assertTrue(empty != result);
+ }
+
+ //-----------------------------------------------------------------------
+
+ public void testSubarrayObject() {
+ Object[] nullArray = null;
+ Object[] objectArray = { "a", "b", "c", "d", "e", "f"};
+
+ assertEquals("0 start, mid end", "abcd",
+ StringUtils.join(ArrayUtils.subarray(objectArray, 0, 4)));
+ assertEquals("0 start, length end", "abcdef",
+ StringUtils.join(ArrayUtils.subarray(objectArray, 0, objectArray.length)));
+ assertEquals("mid start, mid end", "bcd",
+ StringUtils.join(ArrayUtils.subarray(objectArray, 1, 4)));
+ assertEquals("mid start, length end", "bcdef",
+ StringUtils.join(ArrayUtils.subarray(objectArray, 1, objectArray.length)));
+
+ assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3));
+ assertEquals("empty array", "",
+ StringUtils.join(ArrayUtils.subarray(ArrayUtils.EMPTY_OBJECT_ARRAY, 1, 2)));
+ assertEquals("start > end", "",
+ StringUtils.join(ArrayUtils.subarray(objectArray, 4, 2)));
+ assertEquals("start == end", "",
+ StringUtils.join(ArrayUtils.subarray(objectArray, 3, 3)));
+ assertEquals("start undershoot, normal end", "abcd",
+ StringUtils.join(ArrayUtils.subarray(objectArray, -2, 4)));
+ assertEquals("start overshoot, any end", "",
+ StringUtils.join(ArrayUtils.subarray(objectArray, 33, 4)));
+ assertEquals("normal start, end overshoot", "cdef",
+ StringUtils.join(ArrayUtils.subarray(objectArray, 2, 33)));
+ assertEquals("start undershoot, end overshoot", "abcdef",
+ StringUtils.join(ArrayUtils.subarray(objectArray, -2, 12)));
+
+ // array type tests
+ Date[] dateArray = { new java.sql.Date(new Date().getTime()),
+ new Date(), new Date(), new Date(), new Date() };
+
+ assertSame("Object type", Object.class,
+ ArrayUtils.subarray(objectArray, 2, 4).getClass().getComponentType());
+ assertSame("java.util.Date type", java.util.Date.class,
+ ArrayUtils.subarray(dateArray, 1, 4).getClass().getComponentType());
+ assertNotSame("java.sql.Date type", java.sql.Date.class,
+ ArrayUtils.subarray(dateArray, 1, 4).getClass().getComponentType());
+ try {
+ @SuppressWarnings("unused")
+ java.sql.Date[] dummy = (java.sql.Date[])ArrayUtils.subarray(dateArray, 1,3);
+ fail("Invalid downcast");
+ } catch (ClassCastException e) {}
+ }
+
+ public void testSubarrayLong() {
+ long[] nullArray = null;
+ long[] array = { 999910, 999911, 999912, 999913, 999914, 999915 };
+ long[] leftSubarray = { 999910, 999911, 999912, 999913 };
+ long[] midSubarray = { 999911, 999912, 999913, 999914 };
+ long[] rightSubarray = { 999912, 999913, 999914, 999915 };
+
+ assertTrue("0 start, mid end",
+ ArrayUtils.isEquals(leftSubarray,
+ ArrayUtils.subarray(array, 0, 4)));
+
+ assertTrue("0 start, length end",
+ ArrayUtils.isEquals(array,
+ ArrayUtils.subarray(array, 0, array.length)));
+
+ assertTrue("mid start, mid end",
+ ArrayUtils.isEquals(midSubarray,
+ ArrayUtils.subarray(array, 1, 5)));
+
+ assertTrue("mid start, length end",
+ ArrayUtils.isEquals(rightSubarray,
+ ArrayUtils.subarray(array, 2, array.length)));
+
+
+ assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3));
+
+ assertEquals("empty array", ArrayUtils.EMPTY_LONG_ARRAY,
+ ArrayUtils.subarray(ArrayUtils.EMPTY_LONG_ARRAY, 1, 2));
+
+ assertEquals("start > end", ArrayUtils.EMPTY_LONG_ARRAY,
+ ArrayUtils.subarray(array, 4, 2));
+
+ assertEquals("start == end", ArrayUtils.EMPTY_LONG_ARRAY,
+ ArrayUtils.subarray(array, 3, 3));
+
+ assertTrue("start undershoot, normal end",
+ ArrayUtils.isEquals(leftSubarray,
+ ArrayUtils.subarray(array, -2, 4)));
+
+ assertEquals("start overshoot, any end",
+ ArrayUtils.EMPTY_LONG_ARRAY,
+ ArrayUtils.subarray(array, 33, 4));
+
+ assertTrue("normal start, end overshoot",
+ ArrayUtils.isEquals(rightSubarray,
+ ArrayUtils.subarray(array, 2, 33)));
+
+ assertTrue("start undershoot, end overshoot",
+ ArrayUtils.isEquals(array,
+ ArrayUtils.subarray(array, -2, 12)));
+
+ // empty-return tests
+
+ assertSame("empty array, object test",
+ ArrayUtils.EMPTY_LONG_ARRAY,
+ ArrayUtils.subarray(ArrayUtils.EMPTY_LONG_ARRAY, 1, 2));
+
+ assertSame("start > end, object test",
+ ArrayUtils.EMPTY_LONG_ARRAY,
+ ArrayUtils.subarray(array, 4, 1));
+
+ assertSame("start == end, object test",
+ ArrayUtils.EMPTY_LONG_ARRAY,
+ ArrayUtils.subarray(array, 3, 3));
+
+ assertSame("start overshoot, any end, object test",
+ ArrayUtils.EMPTY_LONG_ARRAY,
+ ArrayUtils.subarray(array, 8733, 4));
+
+ // array type tests
+
+ assertSame("long type", long.class,
+ ArrayUtils.subarray(array, 2, 4).getClass().getComponentType());
+
+ }
+
+ public void testSubarrayInt() {
+ int[] nullArray = null;
+ int[] array = { 10, 11, 12, 13, 14, 15 };
+ int[] leftSubarray = { 10, 11, 12, 13 };
+ int[] midSubarray = { 11, 12, 13, 14 };
+ int[] rightSubarray = { 12, 13, 14, 15 };
+
+
+ assertTrue("0 start, mid end",
+ ArrayUtils.isEquals(leftSubarray,
+ ArrayUtils.subarray(array, 0, 4)));
+
+ assertTrue("0 start, length end",
+ ArrayUtils.isEquals(array,
+ ArrayUtils.subarray(array, 0, array.length)));
+
+ assertTrue("mid start, mid end",
+ ArrayUtils.isEquals(midSubarray,
+ ArrayUtils.subarray(array, 1, 5)));
+
+ assertTrue("mid start, length end",
+ ArrayUtils.isEquals(rightSubarray,
+ ArrayUtils.subarray(array, 2, array.length)));
+
+
+ assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3));
+
+ assertEquals("empty array", ArrayUtils.EMPTY_INT_ARRAY,
+ ArrayUtils.subarray(ArrayUtils.EMPTY_INT_ARRAY, 1, 2));
+
+ assertEquals("start > end", ArrayUtils.EMPTY_INT_ARRAY,
+ ArrayUtils.subarray(array, 4, 2));
+
+ assertEquals("start == end", ArrayUtils.EMPTY_INT_ARRAY,
+ ArrayUtils.subarray(array, 3, 3));
+
+ assertTrue("start undershoot, normal end",
+ ArrayUtils.isEquals(leftSubarray,
+ ArrayUtils.subarray(array, -2, 4)));
+
+ assertEquals("start overshoot, any end",
+ ArrayUtils.EMPTY_INT_ARRAY,
+ ArrayUtils.subarray(array, 33, 4));
+
+ assertTrue("normal start, end overshoot",
+ ArrayUtils.isEquals(rightSubarray,
+ ArrayUtils.subarray(array, 2, 33)));
+
+ assertTrue("start undershoot, end overshoot",
+ ArrayUtils.isEquals(array,
+ ArrayUtils.subarray(array, -2, 12)));
+
+ // empty-return tests
+
+ assertSame("empty array, object test",
+ ArrayUtils.EMPTY_INT_ARRAY,
+ ArrayUtils.subarray(ArrayUtils.EMPTY_INT_ARRAY, 1, 2));
+
+ assertSame("start > end, object test",
+ ArrayUtils.EMPTY_INT_ARRAY,
+ ArrayUtils.subarray(array, 4, 1));
+
+ assertSame("start == end, object test",
+ ArrayUtils.EMPTY_INT_ARRAY,
+ ArrayUtils.subarray(array, 3, 3));
+
+ assertSame("start overshoot, any end, object test",
+ ArrayUtils.EMPTY_INT_ARRAY,
+ ArrayUtils.subarray(array, 8733, 4));
+
+ // array type tests
+
+ assertSame("int type", int.class,
+ ArrayUtils.subarray(array, 2, 4).getClass().getComponentType());
+
+ }
+
+ public void testSubarrayShort() {
+ short[] nullArray = null;
+ short[] array = { 10, 11, 12, 13, 14, 15 };
+ short[] leftSubarray = { 10, 11, 12, 13 };
+ short[] midSubarray = { 11, 12, 13, 14 };
+ short[] rightSubarray = { 12, 13, 14, 15 };
+
+
+ assertTrue("0 start, mid end",
+ ArrayUtils.isEquals(leftSubarray,
+ ArrayUtils.subarray(array, 0, 4)));
+
+ assertTrue("0 start, length end",
+ ArrayUtils.isEquals(array,
+ ArrayUtils.subarray(array, 0, array.length)));
+
+ assertTrue("mid start, mid end",
+ ArrayUtils.isEquals(midSubarray,
+ ArrayUtils.subarray(array, 1, 5)));
+
+ assertTrue("mid start, length end",
+ ArrayUtils.isEquals(rightSubarray,
+ ArrayUtils.subarray(array, 2, array.length)));
+
+
+ assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3));
+
+ assertEquals("empty array", ArrayUtils.EMPTY_SHORT_ARRAY,
+ ArrayUtils.subarray(ArrayUtils.EMPTY_SHORT_ARRAY, 1, 2));
+
+ assertEquals("start > end", ArrayUtils.EMPTY_SHORT_ARRAY,
+ ArrayUtils.subarray(array, 4, 2));
+
+ assertEquals("start == end", ArrayUtils.EMPTY_SHORT_ARRAY,
+ ArrayUtils.subarray(array, 3, 3));
+
+ assertTrue("start undershoot, normal end",
+ ArrayUtils.isEquals(leftSubarray,
+ ArrayUtils.subarray(array, -2, 4)));
+
+ assertEquals("start overshoot, any end",
+ ArrayUtils.EMPTY_SHORT_ARRAY,
+ ArrayUtils.subarray(array, 33, 4));
+
+ assertTrue("normal start, end overshoot",
+ ArrayUtils.isEquals(rightSubarray,
+ ArrayUtils.subarray(array, 2, 33)));
+
+ assertTrue("start undershoot, end overshoot",
+ ArrayUtils.isEquals(array,
+ ArrayUtils.subarray(array, -2, 12)));
+
+ // empty-return tests
+
+ assertSame("empty array, object test",
+ ArrayUtils.EMPTY_SHORT_ARRAY,
+ ArrayUtils.subarray(ArrayUtils.EMPTY_SHORT_ARRAY, 1, 2));
+
+ assertSame("start > end, object test",
+ ArrayUtils.EMPTY_SHORT_ARRAY,
+ ArrayUtils.subarray(array, 4, 1));
+
+ assertSame("start == end, object test",
+ ArrayUtils.EMPTY_SHORT_ARRAY,
+ ArrayUtils.subarray(array, 3, 3));
+
+ assertSame("start overshoot, any end, object test",
+ ArrayUtils.EMPTY_SHORT_ARRAY,
+ ArrayUtils.subarray(array, 8733, 4));
+
+ // array type tests
+
+ assertSame("short type", short.class,
+ ArrayUtils.subarray(array, 2, 4).getClass().getComponentType());
+
+ }
+
+ public void testSubarrChar() {
+ char[] nullArray = null;
+ char[] array = { 'a', 'b', 'c', 'd', 'e', 'f' };
+ char[] leftSubarray = { 'a', 'b', 'c', 'd', };
+ char[] midSubarray = { 'b', 'c', 'd', 'e', };
+ char[] rightSubarray = { 'c', 'd', 'e', 'f', };
+
+
+ assertTrue("0 start, mid end",
+ ArrayUtils.isEquals(leftSubarray,
+ ArrayUtils.subarray(array, 0, 4)));
+
+ assertTrue("0 start, length end",
+ ArrayUtils.isEquals(array,
+ ArrayUtils.subarray(array, 0, array.length)));
+
+ assertTrue("mid start, mid end",
+ ArrayUtils.isEquals(midSubarray,
+ ArrayUtils.subarray(array, 1, 5)));
+
+ assertTrue("mid start, length end",
+ ArrayUtils.isEquals(rightSubarray,
+ ArrayUtils.subarray(array, 2, array.length)));
+
+
+ assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3));
+
+ assertEquals("empty array", ArrayUtils.EMPTY_CHAR_ARRAY,
+ ArrayUtils.subarray(ArrayUtils.EMPTY_CHAR_ARRAY, 1, 2));
+
+ assertEquals("start > end", ArrayUtils.EMPTY_CHAR_ARRAY,
+ ArrayUtils.subarray(array, 4, 2));
+
+ assertEquals("start == end", ArrayUtils.EMPTY_CHAR_ARRAY,
+ ArrayUtils.subarray(array, 3, 3));
+
+ assertTrue("start undershoot, normal end",
+ ArrayUtils.isEquals(leftSubarray,
+ ArrayUtils.subarray(array, -2, 4)));
+
+ assertEquals("start overshoot, any end",
+ ArrayUtils.EMPTY_CHAR_ARRAY,
+ ArrayUtils.subarray(array, 33, 4));
+
+ assertTrue("normal start, end overshoot",
+ ArrayUtils.isEquals(rightSubarray,
+ ArrayUtils.subarray(array, 2, 33)));
+
+ assertTrue("start undershoot, end overshoot",
+ ArrayUtils.isEquals(array,
+ ArrayUtils.subarray(array, -2, 12)));
+
+ // empty-return tests
+
+ assertSame("empty array, object test",
+ ArrayUtils.EMPTY_CHAR_ARRAY,
+ ArrayUtils.subarray(ArrayUtils.EMPTY_CHAR_ARRAY, 1, 2));
+
+ assertSame("start > end, object test",
+ ArrayUtils.EMPTY_CHAR_ARRAY,
+ ArrayUtils.subarray(array, 4, 1));
+
+ assertSame("start == end, object test",
+ ArrayUtils.EMPTY_CHAR_ARRAY,
+ ArrayUtils.subarray(array, 3, 3));
+
+ assertSame("start overshoot, any end, object test",
+ ArrayUtils.EMPTY_CHAR_ARRAY,
+ ArrayUtils.subarray(array, 8733, 4));
+
+ // array type tests
+
+ assertSame("char type", char.class,
+ ArrayUtils.subarray(array, 2, 4).getClass().getComponentType());
+
+ }
+
+ public void testSubarrayByte() {
+ byte[] nullArray = null;
+ byte[] array = { 10, 11, 12, 13, 14, 15 };
+ byte[] leftSubarray = { 10, 11, 12, 13 };
+ byte[] midSubarray = { 11, 12, 13, 14 };
+ byte[] rightSubarray = { 12, 13, 14, 15 };
+
+
+ assertTrue("0 start, mid end",
+ ArrayUtils.isEquals(leftSubarray,
+ ArrayUtils.subarray(array, 0, 4)));
+
+ assertTrue("0 start, length end",
+ ArrayUtils.isEquals(array,
+ ArrayUtils.subarray(array, 0, array.length)));
+
+ assertTrue("mid start, mid end",
+ ArrayUtils.isEquals(midSubarray,
+ ArrayUtils.subarray(array, 1, 5)));
+
+ assertTrue("mid start, length end",
+ ArrayUtils.isEquals(rightSubarray,
+ ArrayUtils.subarray(array, 2, array.length)));
+
+
+ assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3));
+
+ assertEquals("empty array", ArrayUtils.EMPTY_BYTE_ARRAY,
+ ArrayUtils.subarray(ArrayUtils.EMPTY_BYTE_ARRAY, 1, 2));
+
+ assertEquals("start > end", ArrayUtils.EMPTY_BYTE_ARRAY,
+ ArrayUtils.subarray(array, 4, 2));
+
+ assertEquals("start == end", ArrayUtils.EMPTY_BYTE_ARRAY,
+ ArrayUtils.subarray(array, 3, 3));
+
+ assertTrue("start undershoot, normal end",
+ ArrayUtils.isEquals(leftSubarray,
+ ArrayUtils.subarray(array, -2, 4)));
+
+ assertEquals("start overshoot, any end",
+ ArrayUtils.EMPTY_BYTE_ARRAY,
+ ArrayUtils.subarray(array, 33, 4));
+
+ assertTrue("normal start, end overshoot",
+ ArrayUtils.isEquals(rightSubarray,
+ ArrayUtils.subarray(array, 2, 33)));
+
+ assertTrue("start undershoot, end overshoot",
+ ArrayUtils.isEquals(array,
+ ArrayUtils.subarray(array, -2, 12)));
+
+ // empty-return tests
+
+ assertSame("empty array, object test",
+ ArrayUtils.EMPTY_BYTE_ARRAY,
+ ArrayUtils.subarray(ArrayUtils.EMPTY_BYTE_ARRAY, 1, 2));
+
+ assertSame("start > end, object test",
+ ArrayUtils.EMPTY_BYTE_ARRAY,
+ ArrayUtils.subarray(array, 4, 1));
+
+ assertSame("start == end, object test",
+ ArrayUtils.EMPTY_BYTE_ARRAY,
+ ArrayUtils.subarray(array, 3, 3));
+
+ assertSame("start overshoot, any end, object test",
+ ArrayUtils.EMPTY_BYTE_ARRAY,
+ ArrayUtils.subarray(array, 8733, 4));
+
+ // array type tests
+
+ assertSame("byte type", byte.class,
+ ArrayUtils.subarray(array, 2, 4).getClass().getComponentType());
+
+ }
+
+ public void testSubarrayDouble() {
+ double[] nullArray = null;
+ double[] array = { 10.123, 11.234, 12.345, 13.456, 14.567, 15.678 };
+ double[] leftSubarray = { 10.123, 11.234, 12.345, 13.456, };
+ double[] midSubarray = { 11.234, 12.345, 13.456, 14.567, };
+ double[] rightSubarray = { 12.345, 13.456, 14.567, 15.678 };
+
+
+ assertTrue("0 start, mid end",
+ ArrayUtils.isEquals(leftSubarray,
+ ArrayUtils.subarray(array, 0, 4)));
+
+ assertTrue("0 start, length end",
+ ArrayUtils.isEquals(array,
+ ArrayUtils.subarray(array, 0, array.length)));
+
+ assertTrue("mid start, mid end",
+ ArrayUtils.isEquals(midSubarray,
+ ArrayUtils.subarray(array, 1, 5)));
+
+ assertTrue("mid start, length end",
+ ArrayUtils.isEquals(rightSubarray,
+ ArrayUtils.subarray(array, 2, array.length)));
+
+
+ assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3));
+
+ assertEquals("empty array", ArrayUtils.EMPTY_DOUBLE_ARRAY,
+ ArrayUtils.subarray(ArrayUtils.EMPTY_DOUBLE_ARRAY, 1, 2));
+
+ assertEquals("start > end", ArrayUtils.EMPTY_DOUBLE_ARRAY,
+ ArrayUtils.subarray(array, 4, 2));
+
+ assertEquals("start == end", ArrayUtils.EMPTY_DOUBLE_ARRAY,
+ ArrayUtils.subarray(array, 3, 3));
+
+ assertTrue("start undershoot, normal end",
+ ArrayUtils.isEquals(leftSubarray,
+ ArrayUtils.subarray(array, -2, 4)));
+
+ assertEquals("start overshoot, any end",
+ ArrayUtils.EMPTY_DOUBLE_ARRAY,
+ ArrayUtils.subarray(array, 33, 4));
+
+ assertTrue("normal start, end overshoot",
+ ArrayUtils.isEquals(rightSubarray,
+ ArrayUtils.subarray(array, 2, 33)));
+
+ assertTrue("start undershoot, end overshoot",
+ ArrayUtils.isEquals(array,
+ ArrayUtils.subarray(array, -2, 12)));
+
+ // empty-return tests
+
+ assertSame("empty array, object test",
+ ArrayUtils.EMPTY_DOUBLE_ARRAY,
+ ArrayUtils.subarray(ArrayUtils.EMPTY_DOUBLE_ARRAY, 1, 2));
+
+ assertSame("start > end, object test",
+ ArrayUtils.EMPTY_DOUBLE_ARRAY,
+ ArrayUtils.subarray(array, 4, 1));
+
+ assertSame("start == end, object test",
+ ArrayUtils.EMPTY_DOUBLE_ARRAY,
+ ArrayUtils.subarray(array, 3, 3));
+
+ assertSame("start overshoot, any end, object test",
+ ArrayUtils.EMPTY_DOUBLE_ARRAY,
+ ArrayUtils.subarray(array, 8733, 4));
+
+ // array type tests
+
+ assertSame("double type", double.class,
+ ArrayUtils.subarray(array, 2, 4).getClass().getComponentType());
+
+ }
+
+ public void testSubarrayFloat() {
+ float[] nullArray = null;
+ float[] array = { 10, 11, 12, 13, 14, 15 };
+ float[] leftSubarray = { 10, 11, 12, 13 };
+ float[] midSubarray = { 11, 12, 13, 14 };
+ float[] rightSubarray = { 12, 13, 14, 15 };
+
+
+ assertTrue("0 start, mid end",
+ ArrayUtils.isEquals(leftSubarray,
+ ArrayUtils.subarray(array, 0, 4)));
+
+ assertTrue("0 start, length end",
+ ArrayUtils.isEquals(array,
+ ArrayUtils.subarray(array, 0, array.length)));
+
+ assertTrue("mid start, mid end",
+ ArrayUtils.isEquals(midSubarray,
+ ArrayUtils.subarray(array, 1, 5)));
+
+ assertTrue("mid start, length end",
+ ArrayUtils.isEquals(rightSubarray,
+ ArrayUtils.subarray(array, 2, array.length)));
+
+
+ assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3));
+
+ assertEquals("empty array", ArrayUtils.EMPTY_FLOAT_ARRAY,
+ ArrayUtils.subarray(ArrayUtils.EMPTY_FLOAT_ARRAY, 1, 2));
+
+ assertEquals("start > end", ArrayUtils.EMPTY_FLOAT_ARRAY,
+ ArrayUtils.subarray(array, 4, 2));
+
+ assertEquals("start == end", ArrayUtils.EMPTY_FLOAT_ARRAY,
+ ArrayUtils.subarray(array, 3, 3));
+
+ assertTrue("start undershoot, normal end",
+ ArrayUtils.isEquals(leftSubarray,
+ ArrayUtils.subarray(array, -2, 4)));
+
+ assertEquals("start overshoot, any end",
+ ArrayUtils.EMPTY_FLOAT_ARRAY,
+ ArrayUtils.subarray(array, 33, 4));
+
+ assertTrue("normal start, end overshoot",
+ ArrayUtils.isEquals(rightSubarray,
+ ArrayUtils.subarray(array, 2, 33)));
+
+ assertTrue("start undershoot, end overshoot",
+ ArrayUtils.isEquals(array,
+ ArrayUtils.subarray(array, -2, 12)));
+
+ // empty-return tests
+
+ assertSame("empty array, object test",
+ ArrayUtils.EMPTY_FLOAT_ARRAY,
+ ArrayUtils.subarray(ArrayUtils.EMPTY_FLOAT_ARRAY, 1, 2));
+
+ assertSame("start > end, object test",
+ ArrayUtils.EMPTY_FLOAT_ARRAY,
+ ArrayUtils.subarray(array, 4, 1));
+
+ assertSame("start == end, object test",
+ ArrayUtils.EMPTY_FLOAT_ARRAY,
+ ArrayUtils.subarray(array, 3, 3));
+
+ assertSame("start overshoot, any end, object test",
+ ArrayUtils.EMPTY_FLOAT_ARRAY,
+ ArrayUtils.subarray(array, 8733, 4));
+
+ // array type tests
+
+ assertSame("float type", float.class,
+ ArrayUtils.subarray(array, 2, 4).getClass().getComponentType());
+
+ }
+
+ public void testSubarrayBoolean() {
+ boolean[] nullArray = null;
+ boolean[] array = { true, true, false, true, false, true };
+ boolean[] leftSubarray = { true, true, false, true };
+ boolean[] midSubarray = { true, false, true, false };
+ boolean[] rightSubarray = { false, true, false, true };
+
+
+ assertTrue("0 start, mid end",
+ ArrayUtils.isEquals(leftSubarray,
+ ArrayUtils.subarray(array, 0, 4)));
+
+ assertTrue("0 start, length end",
+ ArrayUtils.isEquals(array,
+ ArrayUtils.subarray(array, 0, array.length)));
+
+ assertTrue("mid start, mid end",
+ ArrayUtils.isEquals(midSubarray,
+ ArrayUtils.subarray(array, 1, 5)));
+
+ assertTrue("mid start, length end",
+ ArrayUtils.isEquals(rightSubarray,
+ ArrayUtils.subarray(array, 2, array.length)));
+
+
+ assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3));
+
+ assertEquals("empty array", ArrayUtils.EMPTY_BOOLEAN_ARRAY,
+ ArrayUtils.subarray(ArrayUtils.EMPTY_BOOLEAN_ARRAY, 1, 2));
+
+ assertEquals("start > end", ArrayUtils.EMPTY_BOOLEAN_ARRAY,
+ ArrayUtils.subarray(array, 4, 2));
+
+ assertEquals("start == end", ArrayUtils.EMPTY_BOOLEAN_ARRAY,
+ ArrayUtils.subarray(array, 3, 3));
+
+ assertTrue("start undershoot, normal end",
+ ArrayUtils.isEquals(leftSubarray,
+ ArrayUtils.subarray(array, -2, 4)));
+
+ assertEquals("start overshoot, any end",
+ ArrayUtils.EMPTY_BOOLEAN_ARRAY,
+ ArrayUtils.subarray(array, 33, 4));
+
+ assertTrue("normal start, end overshoot",
+ ArrayUtils.isEquals(rightSubarray,
+ ArrayUtils.subarray(array, 2, 33)));
+
+ assertTrue("start undershoot, end overshoot",
+ ArrayUtils.isEquals(array,
+ ArrayUtils.subarray(array, -2, 12)));
+
+ // empty-return tests
+
+ assertSame("empty array, object test",
+ ArrayUtils.EMPTY_BOOLEAN_ARRAY,
+ ArrayUtils.subarray(ArrayUtils.EMPTY_BOOLEAN_ARRAY, 1, 2));
+
+ assertSame("start > end, object test",
+ ArrayUtils.EMPTY_BOOLEAN_ARRAY,
+ ArrayUtils.subarray(array, 4, 1));
+
+ assertSame("start == end, object test",
+ ArrayUtils.EMPTY_BOOLEAN_ARRAY,
+ ArrayUtils.subarray(array, 3, 3));
+
+ assertSame("start overshoot, any end, object test",
+ ArrayUtils.EMPTY_BOOLEAN_ARRAY,
+ ArrayUtils.subarray(array, 8733, 4));
+
+ // array type tests
+
+ assertSame("boolean type", boolean.class,
+ ArrayUtils.subarray(array, 2, 4).getClass().getComponentType());
+
+ }
+
+ //-----------------------------------------------------------------------
+ public void testSameLength() {
+ Object[] nullArray = null;
+ Object[] emptyArray = new Object[0];
+ Object[] oneArray = new Object[] {"pick"};
+ Object[] twoArray = new Object[] {"pick", "stick"};
+
+ assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray));
+ assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray));
+
+ assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray));
+ assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray));
+
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray));
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray));
+ assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray));
+
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray));
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray));
+ assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray));
+ }
+
+ public void testSameLengthBoolean() {
+ boolean[] nullArray = null;
+ boolean[] emptyArray = new boolean[0];
+ boolean[] oneArray = new boolean[] {true};
+ boolean[] twoArray = new boolean[] {true, false};
+
+ assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray));
+ assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray));
+
+ assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray));
+ assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray));
+
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray));
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray));
+ assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray));
+
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray));
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray));
+ assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray));
+ }
+
+ public void testSameLengthLong() {
+ long[] nullArray = null;
+ long[] emptyArray = new long[0];
+ long[] oneArray = new long[] {0L};
+ long[] twoArray = new long[] {0L, 76L};
+
+ assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray));
+ assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray));
+
+ assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray));
+ assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray));
+
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray));
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray));
+ assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray));
+
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray));
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray));
+ assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray));
+ }
+
+ public void testSameLengthInt() {
+ int[] nullArray = null;
+ int[] emptyArray = new int[0];
+ int[] oneArray = new int[] {4};
+ int[] twoArray = new int[] {5, 7};
+
+ assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray));
+ assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray));
+
+ assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray));
+ assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray));
+
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray));
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray));
+ assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray));
+
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray));
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray));
+ assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray));
+ }
+
+ public void testSameLengthShort() {
+ short[] nullArray = null;
+ short[] emptyArray = new short[0];
+ short[] oneArray = new short[] {4};
+ short[] twoArray = new short[] {6, 8};
+
+ assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray));
+ assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray));
+
+ assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray));
+ assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray));
+
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray));
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray));
+ assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray));
+
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray));
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray));
+ assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray));
+ }
+
+ public void testSameLengthChar() {
+ char[] nullArray = null;
+ char[] emptyArray = new char[0];
+ char[] oneArray = new char[] {'f'};
+ char[] twoArray = new char[] {'d', 't'};
+
+ assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray));
+ assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray));
+
+ assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray));
+ assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray));
+
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray));
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray));
+ assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray));
+
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray));
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray));
+ assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray));
+ }
+
+ public void testSameLengthByte() {
+ byte[] nullArray = null;
+ byte[] emptyArray = new byte[0];
+ byte[] oneArray = new byte[] {3};
+ byte[] twoArray = new byte[] {4, 6};
+
+ assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray));
+ assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray));
+
+ assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray));
+ assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray));
+
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray));
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray));
+ assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray));
+
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray));
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray));
+ assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray));
+ }
+
+ public void testSameLengthDouble() {
+ double[] nullArray = null;
+ double[] emptyArray = new double[0];
+ double[] oneArray = new double[] {1.3d};
+ double[] twoArray = new double[] {4.5d, 6.3d};
+
+ assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray));
+ assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray));
+
+ assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray));
+ assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray));
+
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray));
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray));
+ assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray));
+
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray));
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray));
+ assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray));
+ }
+
+ public void testSameLengthFloat() {
+ float[] nullArray = null;
+ float[] emptyArray = new float[0];
+ float[] oneArray = new float[] {2.5f};
+ float[] twoArray = new float[] {6.4f, 5.8f};
+
+ assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray));
+ assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray));
+
+ assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray));
+ assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray));
+
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray));
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray));
+ assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray));
+ assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray));
+
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray));
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray));
+ assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray));
+ assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray));
+ }
+
+ //-----------------------------------------------------------------------
+ public void testSameType() {
+ try {
+ ArrayUtils.isSameType(null, null);
+ fail();
+ } catch (IllegalArgumentException ex) {}
+ try {
+ ArrayUtils.isSameType(null, new Object[0]);
+ fail();
+ } catch (IllegalArgumentException ex) {}
+ try {
+ ArrayUtils.isSameType(new Object[0], null);
+ fail();
+ } catch (IllegalArgumentException ex) {}
+
+ assertEquals(true, ArrayUtils.isSameType(new Object[0], new Object[0]));
+ assertEquals(false, ArrayUtils.isSameType(new String[0], new Object[0]));
+ assertEquals(true, ArrayUtils.isSameType(new String[0][0], new String[0][0]));
+ assertEquals(false, ArrayUtils.isSameType(new String[0], new String[0][0]));
+ assertEquals(false, ArrayUtils.isSameType(new String[0][0], new String[0]));
+ }
+
+ //-----------------------------------------------------------------------
+ public void testReverse() {
+ StringBuffer str1 = new StringBuffer("pick");
+ String str2 = "a";
+ String[] str3 = new String[] {"stick"};
+ String str4 = "up";
+
+ Object[] array = new Object[] {str1, str2, str3};
+ ArrayUtils.reverse(array);
+ assertEquals(array[0], str3);
+ assertEquals(array[1], str2);
+ assertEquals(array[2], str1);
+
+ array = new Object[] {str1, str2, str3, str4};
+ ArrayUtils.reverse(array);
+ assertEquals(array[0], str4);
+ assertEquals(array[1], str3);
+ assertEquals(array[2], str2);
+ assertEquals(array[3], str1);
+
+ array = null;
+ ArrayUtils.reverse(array);
+ assertEquals(null, array);
+ }
+
+ public void testReverseLong() {
+ long[] array = new long[] {1L, 2L, 3L};
+ ArrayUtils.reverse(array);
+ assertEquals(array[0], 3L);
+ assertEquals(array[1], 2L);
+ assertEquals(array[2], 1L);
+
+ array = null;
+ ArrayUtils.reverse(array);
+ assertEquals(null, array);
+ }
+
+ public void testReverseInt() {
+ int[] array = new int[] {1, 2, 3};
+ ArrayUtils.reverse(array);
+ assertEquals(array[0], 3);
+ assertEquals(array[1], 2);
+ assertEquals(array[2], 1);
+
+ array = null;
+ ArrayUtils.reverse(array);
+ assertEquals(null, array);
+ }
+
+ public void testReverseShort() {
+ short[] array = new short[] {1, 2, 3};
+ ArrayUtils.reverse(array);
+ assertEquals(array[0], 3);
+ assertEquals(array[1], 2);
+ assertEquals(array[2], 1);
+
+ array = null;
+ ArrayUtils.reverse(array);
+ assertEquals(null, array);
+ }
+
+ public void testReverseChar() {
+ char[] array = new char[] {'a', 'f', 'C'};
+ ArrayUtils.reverse(array);
+ assertEquals(array[0], 'C');
+ assertEquals(array[1], 'f');
+ assertEquals(array[2], 'a');
+
+ array = null;
+ ArrayUtils.reverse(array);
+ assertEquals(null, array);
+ }
+
+ public void testReverseByte() {
+ byte[] array = new byte[] {2, 3, 4};
+ ArrayUtils.reverse(array);
+ assertEquals(array[0], 4);
+ assertEquals(array[1], 3);
+ assertEquals(array[2], 2);
+
+ array = null;
+ ArrayUtils.reverse(array);
+ assertEquals(null, array);
+ }
+
+ public void testReverseDouble() {
+ double[] array = new double[] {0.3d, 0.4d, 0.5d};
+ ArrayUtils.reverse(array);
+ assertEquals(array[0], 0.5d, 0.0d);
+ assertEquals(array[1], 0.4d, 0.0d);
+ assertEquals(array[2], 0.3d, 0.0d);
+
+ array = null;
+ ArrayUtils.reverse(array);
+ assertEquals(null, array);
+ }
+
+ public void testReverseFloat() {
+ float[] array = new float[] {0.3f, 0.4f, 0.5f};
+ ArrayUtils.reverse(array);
+ assertEquals(array[0], 0.5f, 0.0f);
+ assertEquals(array[1], 0.4f, 0.0f);
+ assertEquals(array[2], 0.3f, 0.0f);
+
+ array = null;
+ ArrayUtils.reverse(array);
+ assertEquals(null, array);
+ }
+
+ public void testReverseBoolean() {
+ boolean[] array = new boolean[] {false, false, true};
+ ArrayUtils.reverse(array);
+ assertEquals(array[0], true);
+ assertEquals(array[1], false);
+ assertEquals(array[2], false);
+
+ array = null;
+ ArrayUtils.reverse(array);
+ assertEquals(null, array);
+ }
+
+ //-----------------------------------------------------------------------
+ public void testIndexOf() {
+ Object[] array = new Object[] { "0", "1", "2", "3", null, "0" };
+ assertEquals(-1, ArrayUtils.indexOf(null, null));
+ assertEquals(-1, ArrayUtils.indexOf(null, "0"));
+ assertEquals(-1, ArrayUtils.indexOf(new Object[0], "0"));
+ assertEquals(0, ArrayUtils.indexOf(array, "0"));
+ assertEquals(1, ArrayUtils.indexOf(array, "1"));
+ assertEquals(2, ArrayUtils.indexOf(array, "2"));
+ assertEquals(3, ArrayUtils.indexOf(array, "3"));
+ assertEquals(4, ArrayUtils.indexOf(array, null));
+ assertEquals(-1, ArrayUtils.indexOf(array, "notInArray"));
+ }
+
+ public void testIndexOfWithStartIndex() {
+ Object[] array = new Object[] { "0", "1", "2", "3", null, "0" };
+ assertEquals(-1, ArrayUtils.indexOf(null, null, 2));
+ assertEquals(-1, ArrayUtils.indexOf(new Object[0], "0", 0));
+ assertEquals(-1, ArrayUtils.indexOf(null, "0", 2));
+ assertEquals(5, ArrayUtils.indexOf(array, "0", 2));
+ assertEquals(-1, ArrayUtils.indexOf(array, "1", 2));
+ assertEquals(2, ArrayUtils.indexOf(array, "2", 2));
+ assertEquals(3, ArrayUtils.indexOf(array, "3", 2));
+ assertEquals(4, ArrayUtils.indexOf(array, null, 2));
+ assertEquals(-1, ArrayUtils.indexOf(array, "notInArray", 2));
+
+ assertEquals(4, ArrayUtils.indexOf(array, null, -1));
+ assertEquals(-1, ArrayUtils.indexOf(array, null, 8));
+ assertEquals(-1, ArrayUtils.indexOf(array, "0", 8));
+ }
+
+ public void testLastIndexOf() {
+ Object[] array = new Object[] { "0", "1", "2", "3", null, "0" };
+ assertEquals(-1, ArrayUtils.lastIndexOf(null, null));
+ assertEquals(-1, ArrayUtils.lastIndexOf(null, "0"));
+ assertEquals(5, ArrayUtils.lastIndexOf(array, "0"));
+ assertEquals(1, ArrayUtils.lastIndexOf(array, "1"));
+ assertEquals(2, ArrayUtils.lastIndexOf(array, "2"));
+ assertEquals(3, ArrayUtils.lastIndexOf(array, "3"));
+ assertEquals(4, ArrayUtils.lastIndexOf(array, null));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, "notInArray"));
+ }
+
+ public void testLastIndexOfWithStartIndex() {
+ Object[] array = new Object[] { "0", "1", "2", "3", null, "0" };
+ assertEquals(-1, ArrayUtils.lastIndexOf(null, null, 2));
+ assertEquals(-1, ArrayUtils.lastIndexOf(null, "0", 2));
+ assertEquals(0, ArrayUtils.lastIndexOf(array, "0", 2));
+ assertEquals(1, ArrayUtils.lastIndexOf(array, "1", 2));
+ assertEquals(2, ArrayUtils.lastIndexOf(array, "2", 2));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, "3", 2));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, "3", -1));
+ assertEquals(4, ArrayUtils.lastIndexOf(array, null, 5));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, null, 2));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, "notInArray", 5));
+
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, null, -1));
+ assertEquals(5, ArrayUtils.lastIndexOf(array, "0", 88));
+ }
+
+ public void testContains() {
+ Object[] array = new Object[] { "0", "1", "2", "3", null, "0" };
+ assertEquals(false, ArrayUtils.contains(null, null));
+ assertEquals(false, ArrayUtils.contains(null, "1"));
+ assertEquals(true, ArrayUtils.contains(array, "0"));
+ assertEquals(true, ArrayUtils.contains(array, "1"));
+ assertEquals(true, ArrayUtils.contains(array, "2"));
+ assertEquals(true, ArrayUtils.contains(array, "3"));
+ assertEquals(true, ArrayUtils.contains(array, null));
+ assertEquals(false, ArrayUtils.contains(array, "notInArray"));
+ }
+
+ //-----------------------------------------------------------------------
+ public void testIndexOfLong() {
+ long[] array = null;
+ assertEquals(-1, ArrayUtils.indexOf(array, 0));
+ array = new long[] { 0, 1, 2, 3, 0 };
+ assertEquals(0, ArrayUtils.indexOf(array, 0));
+ assertEquals(1, ArrayUtils.indexOf(array, 1));
+ assertEquals(2, ArrayUtils.indexOf(array, 2));
+ assertEquals(3, ArrayUtils.indexOf(array, 3));
+ assertEquals(-1, ArrayUtils.indexOf(array, 99));
+ }
+
+ public void testIndexOfLongWithStartIndex() {
+ long[] array = null;
+ assertEquals(-1, ArrayUtils.indexOf(array, 0, 2));
+ array = new long[] { 0, 1, 2, 3, 0 };
+ assertEquals(4, ArrayUtils.indexOf(array, 0, 2));
+ assertEquals(-1, ArrayUtils.indexOf(array, 1, 2));
+ assertEquals(2, ArrayUtils.indexOf(array, 2, 2));
+ assertEquals(3, ArrayUtils.indexOf(array, 3, 2));
+ assertEquals(3, ArrayUtils.indexOf(array, 3, -1));
+ assertEquals(-1, ArrayUtils.indexOf(array, 99, 0));
+ assertEquals(-1, ArrayUtils.indexOf(array, 0, 6));
+ }
+
+ public void testLastIndexOfLong() {
+ long[] array = null;
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, 0));
+ array = new long[] { 0, 1, 2, 3, 0 };
+ assertEquals(4, ArrayUtils.lastIndexOf(array, 0));
+ assertEquals(1, ArrayUtils.lastIndexOf(array, 1));
+ assertEquals(2, ArrayUtils.lastIndexOf(array, 2));
+ assertEquals(3, ArrayUtils.lastIndexOf(array, 3));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, 99));
+ }
+
+ public void testLastIndexOfLongWithStartIndex() {
+ long[] array = null;
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, 0, 2));
+ array = new long[] { 0, 1, 2, 3, 0 };
+ assertEquals(0, ArrayUtils.lastIndexOf(array, 0, 2));
+ assertEquals(1, ArrayUtils.lastIndexOf(array, 1, 2));
+ assertEquals(2, ArrayUtils.lastIndexOf(array, 2, 2));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, 3, 2));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, 3, -1));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, 99, 4));
+ assertEquals(4, ArrayUtils.lastIndexOf(array, 0, 88));
+ }
+
+ public void testContainsLong() {
+ long[] array = null;
+ assertEquals(false, ArrayUtils.contains(array, 1));
+ array = new long[] { 0, 1, 2, 3, 0 };
+ assertEquals(true, ArrayUtils.contains(array, 0));
+ assertEquals(true, ArrayUtils.contains(array, 1));
+ assertEquals(true, ArrayUtils.contains(array, 2));
+ assertEquals(true, ArrayUtils.contains(array, 3));
+ assertEquals(false, ArrayUtils.contains(array, 99));
+ }
+
+ //-----------------------------------------------------------------------
+ public void testIndexOfInt() {
+ int[] array = null;
+ assertEquals(-1, ArrayUtils.indexOf(array, 0));
+ array = new int[] { 0, 1, 2, 3, 0 };
+ assertEquals(0, ArrayUtils.indexOf(array, 0));
+ assertEquals(1, ArrayUtils.indexOf(array, 1));
+ assertEquals(2, ArrayUtils.indexOf(array, 2));
+ assertEquals(3, ArrayUtils.indexOf(array, 3));
+ assertEquals(-1, ArrayUtils.indexOf(array, 99));
+ }
+
+ public void testIndexOfIntWithStartIndex() {
+ int[] array = null;
+ assertEquals(-1, ArrayUtils.indexOf(array, 0, 2));
+ array = new int[] { 0, 1, 2, 3, 0 };
+ assertEquals(4, ArrayUtils.indexOf(array, 0, 2));
+ assertEquals(-1, ArrayUtils.indexOf(array, 1, 2));
+ assertEquals(2, ArrayUtils.indexOf(array, 2, 2));
+ assertEquals(3, ArrayUtils.indexOf(array, 3, 2));
+ assertEquals(3, ArrayUtils.indexOf(array, 3, -1));
+ assertEquals(-1, ArrayUtils.indexOf(array, 99, 0));
+ assertEquals(-1, ArrayUtils.indexOf(array, 0, 6));
+ }
+
+ public void testLastIndexOfInt() {
+ int[] array = null;
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, 0));
+ array = new int[] { 0, 1, 2, 3, 0 };
+ assertEquals(4, ArrayUtils.lastIndexOf(array, 0));
+ assertEquals(1, ArrayUtils.lastIndexOf(array, 1));
+ assertEquals(2, ArrayUtils.lastIndexOf(array, 2));
+ assertEquals(3, ArrayUtils.lastIndexOf(array, 3));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, 99));
+ }
+
+ public void testLastIndexOfIntWithStartIndex() {
+ int[] array = null;
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, 0, 2));
+ array = new int[] { 0, 1, 2, 3, 0 };
+ assertEquals(0, ArrayUtils.lastIndexOf(array, 0, 2));
+ assertEquals(1, ArrayUtils.lastIndexOf(array, 1, 2));
+ assertEquals(2, ArrayUtils.lastIndexOf(array, 2, 2));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, 3, 2));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, 3, -1));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, 99));
+ assertEquals(4, ArrayUtils.lastIndexOf(array, 0, 88));
+ }
+
+ public void testContainsInt() {
+ int[] array = null;
+ assertEquals(false, ArrayUtils.contains(array, 1));
+ array = new int[] { 0, 1, 2, 3, 0 };
+ assertEquals(true, ArrayUtils.contains(array, 0));
+ assertEquals(true, ArrayUtils.contains(array, 1));
+ assertEquals(true, ArrayUtils.contains(array, 2));
+ assertEquals(true, ArrayUtils.contains(array, 3));
+ assertEquals(false, ArrayUtils.contains(array, 99));
+ }
+
+ //-----------------------------------------------------------------------
+ public void testIndexOfShort() {
+ short[] array = null;
+ assertEquals(-1, ArrayUtils.indexOf(array, (short) 0));
+ array = new short[] { 0, 1, 2, 3, 0 };
+ assertEquals(0, ArrayUtils.indexOf(array, (short) 0));
+ assertEquals(1, ArrayUtils.indexOf(array, (short) 1));
+ assertEquals(2, ArrayUtils.indexOf(array, (short) 2));
+ assertEquals(3, ArrayUtils.indexOf(array, (short) 3));
+ assertEquals(-1, ArrayUtils.indexOf(array, (short) 99));
+ }
+
+ public void testIndexOfShortWithStartIndex() {
+ short[] array = null;
+ assertEquals(-1, ArrayUtils.indexOf(array, (short) 0, 2));
+ array = new short[] { 0, 1, 2, 3, 0 };
+ assertEquals(4, ArrayUtils.indexOf(array, (short) 0, 2));
+ assertEquals(-1, ArrayUtils.indexOf(array, (short) 1, 2));
+ assertEquals(2, ArrayUtils.indexOf(array, (short) 2, 2));
+ assertEquals(3, ArrayUtils.indexOf(array, (short) 3, 2));
+ assertEquals(3, ArrayUtils.indexOf(array, (short) 3, -1));
+ assertEquals(-1, ArrayUtils.indexOf(array, (short) 99, 0));
+ assertEquals(-1, ArrayUtils.indexOf(array, (short) 0, 6));
+ }
+
+ public void testLastIndexOfShort() {
+ short[] array = null;
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 0));
+ array = new short[] { 0, 1, 2, 3, 0 };
+ assertEquals(4, ArrayUtils.lastIndexOf(array, (short) 0));
+ assertEquals(1, ArrayUtils.lastIndexOf(array, (short) 1));
+ assertEquals(2, ArrayUtils.lastIndexOf(array, (short) 2));
+ assertEquals(3, ArrayUtils.lastIndexOf(array, (short) 3));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 99));
+ }
+
+ public void testLastIndexOfShortWithStartIndex() {
+ short[] array = null;
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 0, 2));
+ array = new short[] { 0, 1, 2, 3, 0 };
+ assertEquals(0, ArrayUtils.lastIndexOf(array, (short) 0, 2));
+ assertEquals(1, ArrayUtils.lastIndexOf(array, (short) 1, 2));
+ assertEquals(2, ArrayUtils.lastIndexOf(array, (short) 2, 2));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 3, 2));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 3, -1));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 99));
+ assertEquals(4, ArrayUtils.lastIndexOf(array, (short) 0, 88));
+ }
+
+ public void testContainsShort() {
+ short[] array = null;
+ assertEquals(false, ArrayUtils.contains(array, (short) 1));
+ array = new short[] { 0, 1, 2, 3, 0 };
+ assertEquals(true, ArrayUtils.contains(array, (short) 0));
+ assertEquals(true, ArrayUtils.contains(array, (short) 1));
+ assertEquals(true, ArrayUtils.contains(array, (short) 2));
+ assertEquals(true, ArrayUtils.contains(array, (short) 3));
+ assertEquals(false, ArrayUtils.contains(array, (short) 99));
+ }
+
+ //-----------------------------------------------------------------------
+ public void testIndexOfChar() {
+ char[] array = null;
+ assertEquals(-1, ArrayUtils.indexOf(array, 'a'));
+ array = new char[] { 'a', 'b', 'c', 'd', 'a' };
+ assertEquals(0, ArrayUtils.indexOf(array, 'a'));
+ assertEquals(1, ArrayUtils.indexOf(array, 'b'));
+ assertEquals(2, ArrayUtils.indexOf(array, 'c'));
+ assertEquals(3, ArrayUtils.indexOf(array, 'd'));
+ assertEquals(-1, ArrayUtils.indexOf(array, 'e'));
+ }
+
+ public void testIndexOfCharWithStartIndex() {
+ char[] array = null;
+ assertEquals(-1, ArrayUtils.indexOf(array, 'a', 2));
+ array = new char[] { 'a', 'b', 'c', 'd', 'a' };
+ assertEquals(4, ArrayUtils.indexOf(array, 'a', 2));
+ assertEquals(-1, ArrayUtils.indexOf(array, 'b', 2));
+ assertEquals(2, ArrayUtils.indexOf(array, 'c', 2));
+ assertEquals(3, ArrayUtils.indexOf(array, 'd', 2));
+ assertEquals(3, ArrayUtils.indexOf(array, 'd', -1));
+ assertEquals(-1, ArrayUtils.indexOf(array, 'e', 0));
+ assertEquals(-1, ArrayUtils.indexOf(array, 'a', 6));
+ }
+
+ public void testLastIndexOfChar() {
+ char[] array = null;
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, 'a'));
+ array = new char[] { 'a', 'b', 'c', 'd', 'a' };
+ assertEquals(4, ArrayUtils.lastIndexOf(array, 'a'));
+ assertEquals(1, ArrayUtils.lastIndexOf(array, 'b'));
+ assertEquals(2, ArrayUtils.lastIndexOf(array, 'c'));
+ assertEquals(3, ArrayUtils.lastIndexOf(array, 'd'));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, 'e'));
+ }
+
+ public void testLastIndexOfCharWithStartIndex() {
+ char[] array = null;
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, 'a', 2));
+ array = new char[] { 'a', 'b', 'c', 'd', 'a' };
+ assertEquals(0, ArrayUtils.lastIndexOf(array, 'a', 2));
+ assertEquals(1, ArrayUtils.lastIndexOf(array, 'b', 2));
+ assertEquals(2, ArrayUtils.lastIndexOf(array, 'c', 2));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, 'd', 2));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, 'd', -1));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, 'e'));
+ assertEquals(4, ArrayUtils.lastIndexOf(array, 'a', 88));
+ }
+
+ public void testContainsChar() {
+ char[] array = null;
+ assertEquals(false, ArrayUtils.contains(array, 'b'));
+ array = new char[] { 'a', 'b', 'c', 'd', 'a' };
+ assertEquals(true, ArrayUtils.contains(array, 'a'));
+ assertEquals(true, ArrayUtils.contains(array, 'b'));
+ assertEquals(true, ArrayUtils.contains(array, 'c'));
+ assertEquals(true, ArrayUtils.contains(array, 'd'));
+ assertEquals(false, ArrayUtils.contains(array, 'e'));
+ }
+
+ //-----------------------------------------------------------------------
+ public void testIndexOfByte() {
+ byte[] array = null;
+ assertEquals(-1, ArrayUtils.indexOf(array, (byte) 0));
+ array = new byte[] { 0, 1, 2, 3, 0 };
+ assertEquals(0, ArrayUtils.indexOf(array, (byte) 0));
+ assertEquals(1, ArrayUtils.indexOf(array, (byte) 1));
+ assertEquals(2, ArrayUtils.indexOf(array, (byte) 2));
+ assertEquals(3, ArrayUtils.indexOf(array, (byte) 3));
+ assertEquals(-1, ArrayUtils.indexOf(array, (byte) 99));
+ }
+
+ public void testIndexOfByteWithStartIndex() {
+ byte[] array = null;
+ assertEquals(-1, ArrayUtils.indexOf(array, (byte) 0, 2));
+ array = new byte[] { 0, 1, 2, 3, 0 };
+ assertEquals(4, ArrayUtils.indexOf(array, (byte) 0, 2));
+ assertEquals(-1, ArrayUtils.indexOf(array, (byte) 1, 2));
+ assertEquals(2, ArrayUtils.indexOf(array, (byte) 2, 2));
+ assertEquals(3, ArrayUtils.indexOf(array, (byte) 3, 2));
+ assertEquals(3, ArrayUtils.indexOf(array, (byte) 3, -1));
+ assertEquals(-1, ArrayUtils.indexOf(array, (byte) 99, 0));
+ assertEquals(-1, ArrayUtils.indexOf(array, (byte) 0, 6));
+ }
+
+ public void testLastIndexOfByte() {
+ byte[] array = null;
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 0));
+ array = new byte[] { 0, 1, 2, 3, 0 };
+ assertEquals(4, ArrayUtils.lastIndexOf(array, (byte) 0));
+ assertEquals(1, ArrayUtils.lastIndexOf(array, (byte) 1));
+ assertEquals(2, ArrayUtils.lastIndexOf(array, (byte) 2));
+ assertEquals(3, ArrayUtils.lastIndexOf(array, (byte) 3));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 99));
+ }
+
+ public void testLastIndexOfByteWithStartIndex() {
+ byte[] array = null;
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 0, 2));
+ array = new byte[] { 0, 1, 2, 3, 0 };
+ assertEquals(0, ArrayUtils.lastIndexOf(array, (byte) 0, 2));
+ assertEquals(1, ArrayUtils.lastIndexOf(array, (byte) 1, 2));
+ assertEquals(2, ArrayUtils.lastIndexOf(array, (byte) 2, 2));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 3, 2));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 3, -1));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 99));
+ assertEquals(4, ArrayUtils.lastIndexOf(array, (byte) 0, 88));
+ }
+
+ public void testContainsByte() {
+ byte[] array = null;
+ assertEquals(false, ArrayUtils.contains(array, (byte) 1));
+ array = new byte[] { 0, 1, 2, 3, 0 };
+ assertEquals(true, ArrayUtils.contains(array, (byte) 0));
+ assertEquals(true, ArrayUtils.contains(array, (byte) 1));
+ assertEquals(true, ArrayUtils.contains(array, (byte) 2));
+ assertEquals(true, ArrayUtils.contains(array, (byte) 3));
+ assertEquals(false, ArrayUtils.contains(array, (byte) 99));
+ }
+
+ //-----------------------------------------------------------------------
+ @SuppressWarnings("cast")
+ public void testIndexOfDouble() {
+ double[] array = null;
+ assertEquals(-1, ArrayUtils.indexOf(array, (double) 0));
+ array = new double[0];
+ assertEquals(-1, ArrayUtils.indexOf(array, (double) 0));
+ array = new double[] { 0, 1, 2, 3, 0 };
+ assertEquals(0, ArrayUtils.indexOf(array, (double) 0));
+ assertEquals(1, ArrayUtils.indexOf(array, (double) 1));
+ assertEquals(2, ArrayUtils.indexOf(array, (double) 2));
+ assertEquals(3, ArrayUtils.indexOf(array, (double) 3));
+ assertEquals(3, ArrayUtils.indexOf(array, (double) 3, -1));
+ assertEquals(-1, ArrayUtils.indexOf(array, (double) 99));
+ }
+
+ @SuppressWarnings("cast")
+ public void testIndexOfDoubleTolerance() {
+ double[] array = null;
+ assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, (double) 0));
+ array = new double[0];
+ assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, (double) 0));
+ array = new double[] { 0, 1, 2, 3, 0 };
+ assertEquals(0, ArrayUtils.indexOf(array, (double) 0, (double) 0.3));
+ assertEquals(2, ArrayUtils.indexOf(array, (double) 2.2, (double) 0.35));
+ assertEquals(3, ArrayUtils.indexOf(array, (double) 4.15, (double) 2.0));
+ assertEquals(1, ArrayUtils.indexOf(array, (double) 1.00001324, (double) 0.0001));
+ }
+
+ @SuppressWarnings("cast")
+ public void testIndexOfDoubleWithStartIndex() {
+ double[] array = null;
+ assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 2));
+ array = new double[0];
+ assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 2));
+ array = new double[] { 0, 1, 2, 3, 0 };
+ assertEquals(4, ArrayUtils.indexOf(array, (double) 0, 2));
+ assertEquals(-1, ArrayUtils.indexOf(array, (double) 1, 2));
+ assertEquals(2, ArrayUtils.indexOf(array, (double) 2, 2));
+ assertEquals(3, ArrayUtils.indexOf(array, (double) 3, 2));
+ assertEquals(-1, ArrayUtils.indexOf(array, (double) 99, 0));
+ assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 6));
+ }
+
+ @SuppressWarnings("cast")
+ public void testIndexOfDoubleWithStartIndexTolerance() {
+ double[] array = null;
+ assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 2, (double) 0));
+ array = new double[0];
+ assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 2, (double) 0));
+ array = new double[] { 0, 1, 2, 3, 0 };
+ assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 99, (double) 0.3));
+ assertEquals(0, ArrayUtils.indexOf(array, (double) 0, 0, (double) 0.3));
+ assertEquals(4, ArrayUtils.indexOf(array, (double) 0, 3, (double) 0.3));
+ assertEquals(2, ArrayUtils.indexOf(array, (double) 2.2, 0, (double) 0.35));
+ assertEquals(3, ArrayUtils.indexOf(array, (double) 4.15, 0, (double) 2.0));
+ assertEquals(1, ArrayUtils.indexOf(array, (double) 1.00001324, 0, (double) 0.0001));
+ assertEquals(3, ArrayUtils.indexOf(array, (double) 4.15, -1, (double) 2.0));
+ assertEquals(1, ArrayUtils.indexOf(array, (double) 1.00001324, -300, (double) 0.0001));
+ }
+
+ @SuppressWarnings("cast")
+ public void testLastIndexOfDouble() {
+ double[] array = null;
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0));
+ array = new double[0];
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0));
+ array = new double[] { 0, 1, 2, 3, 0 };
+ assertEquals(4, ArrayUtils.lastIndexOf(array, (double) 0));
+ assertEquals(1, ArrayUtils.lastIndexOf(array, (double) 1));
+ assertEquals(2, ArrayUtils.lastIndexOf(array, (double) 2));
+ assertEquals(3, ArrayUtils.lastIndexOf(array, (double) 3));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 99));
+ }
+
+ @SuppressWarnings("cast")
+ public void testLastIndexOfDoubleTolerance() {
+ double[] array = null;
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, (double) 0));
+ array = new double[0];
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, (double) 0));
+ array = new double[] { 0, 1, 2, 3, 0 };
+ assertEquals(4, ArrayUtils.lastIndexOf(array, (double) 0, (double) 0.3));
+ assertEquals(2, ArrayUtils.lastIndexOf(array, (double) 2.2, (double) 0.35));
+ assertEquals(3, ArrayUtils.lastIndexOf(array, (double) 4.15, (double) 2.0));
+ assertEquals(1, ArrayUtils.lastIndexOf(array, (double) 1.00001324, (double) 0.0001));
+ }
+
+ @SuppressWarnings("cast")
+ public void testLastIndexOfDoubleWithStartIndex() {
+ double[] array = null;
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, 2));
+ array = new double[0];
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, 2));
+ array = new double[] { 0, 1, 2, 3, 0 };
+ assertEquals(0, ArrayUtils.lastIndexOf(array, (double) 0, 2));
+ assertEquals(1, ArrayUtils.lastIndexOf(array, (double) 1, 2));
+ assertEquals(2, ArrayUtils.lastIndexOf(array, (double) 2, 2));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 3, 2));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 3, -1));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 99));
+ assertEquals(4, ArrayUtils.lastIndexOf(array, (double) 0, 88));
+ }
+
+ @SuppressWarnings("cast")
+ public void testLastIndexOfDoubleWithStartIndexTolerance() {
+ double[] array = null;
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, 2, (double) 0));
+ array = new double[0];
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, 2, (double) 0));
+ array = new double[] { (double) 3 };
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 1, 0, (double) 0));
+ array = new double[] { 0, 1, 2, 3, 0 };
+ assertEquals(4, ArrayUtils.lastIndexOf(array, (double) 0, 99, (double) 0.3));
+ assertEquals(0, ArrayUtils.lastIndexOf(array, (double) 0, 3, (double) 0.3));
+ assertEquals(2, ArrayUtils.lastIndexOf(array, (double) 2.2, 3, (double) 0.35));
+ assertEquals(3, ArrayUtils.lastIndexOf(array, (double) 4.15, array.length, (double) 2.0));
+ assertEquals(1, ArrayUtils.lastIndexOf(array, (double) 1.00001324, array.length, (double) 0.0001));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 4.15, -200, (double) 2.0));
+ }
+
+ @SuppressWarnings("cast")
+ public void testContainsDouble() {
+ double[] array = null;
+ assertEquals(false, ArrayUtils.contains(array, (double) 1));
+ array = new double[] { 0, 1, 2, 3, 0 };
+ assertEquals(true, ArrayUtils.contains(array, (double) 0));
+ assertEquals(true, ArrayUtils.contains(array, (double) 1));
+ assertEquals(true, ArrayUtils.contains(array, (double) 2));
+ assertEquals(true, ArrayUtils.contains(array, (double) 3));
+ assertEquals(false, ArrayUtils.contains(array, (double) 99));
+ }
+
+ @SuppressWarnings("cast")
+ public void testContainsDoubleTolerance() {
+ double[] array = null;
+ assertEquals(false, ArrayUtils.contains(array, (double) 1, (double) 0));
+ array = new double[] { 0, 1, 2, 3, 0 };
+ assertEquals(false, ArrayUtils.contains(array, (double) 4.0, (double) 0.33));
+ assertEquals(false, ArrayUtils.contains(array, (double) 2.5, (double) 0.49));
+ assertEquals(true, ArrayUtils.contains(array, (double) 2.5, (double) 0.50));
+ assertEquals(true, ArrayUtils.contains(array, (double) 2.5, (double) 0.51));
+ }
+
+ //-----------------------------------------------------------------------
+ @SuppressWarnings("cast")
+ public void testIndexOfFloat() {
+ float[] array = null;
+ assertEquals(-1, ArrayUtils.indexOf(array, (float) 0));
+ array = new float[0];
+ assertEquals(-1, ArrayUtils.indexOf(array, (float) 0));
+ array = new float[] { 0, 1, 2, 3, 0 };
+ assertEquals(0, ArrayUtils.indexOf(array, (float) 0));
+ assertEquals(1, ArrayUtils.indexOf(array, (float) 1));
+ assertEquals(2, ArrayUtils.indexOf(array, (float) 2));
+ assertEquals(3, ArrayUtils.indexOf(array, (float) 3));
+ assertEquals(-1, ArrayUtils.indexOf(array, (float) 99));
+ }
+
+ @SuppressWarnings("cast")
+ public void testIndexOfFloatWithStartIndex() {
+ float[] array = null;
+ assertEquals(-1, ArrayUtils.indexOf(array, (float) 0, 2));
+ array = new float[0];
+ assertEquals(-1, ArrayUtils.indexOf(array, (float) 0, 2));
+ array = new float[] { 0, 1, 2, 3, 0 };
+ assertEquals(4, ArrayUtils.indexOf(array, (float) 0, 2));
+ assertEquals(-1, ArrayUtils.indexOf(array, (float) 1, 2));
+ assertEquals(2, ArrayUtils.indexOf(array, (float) 2, 2));
+ assertEquals(3, ArrayUtils.indexOf(array, (float) 3, 2));
+ assertEquals(3, ArrayUtils.indexOf(array, (float) 3, -1));
+ assertEquals(-1, ArrayUtils.indexOf(array, (float) 99, 0));
+ assertEquals(-1, ArrayUtils.indexOf(array, (float) 0, 6));
+ }
+
+ @SuppressWarnings("cast")
+ public void testLastIndexOfFloat() {
+ float[] array = null;
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 0));
+ array = new float[0];
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 0));
+ array = new float[] { 0, 1, 2, 3, 0 };
+ assertEquals(4, ArrayUtils.lastIndexOf(array, (float) 0));
+ assertEquals(1, ArrayUtils.lastIndexOf(array, (float) 1));
+ assertEquals(2, ArrayUtils.lastIndexOf(array, (float) 2));
+ assertEquals(3, ArrayUtils.lastIndexOf(array, (float) 3));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 99));
+ }
+
+ @SuppressWarnings("cast")
+ public void testLastIndexOfFloatWithStartIndex() {
+ float[] array = null;
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 0, 2));
+ array = new float[0];
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 0, 2));
+ array = new float[] { 0, 1, 2, 3, 0 };
+ assertEquals(0, ArrayUtils.lastIndexOf(array, (float) 0, 2));
+ assertEquals(1, ArrayUtils.lastIndexOf(array, (float) 1, 2));
+ assertEquals(2, ArrayUtils.lastIndexOf(array, (float) 2, 2));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 3, 2));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 3, -1));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 99));
+ assertEquals(4, ArrayUtils.lastIndexOf(array, (float) 0, 88));
+ }
+
+ @SuppressWarnings("cast")
+ public void testContainsFloat() {
+ float[] array = null;
+ assertEquals(false, ArrayUtils.contains(array, (float) 1));
+ array = new float[] { 0, 1, 2, 3, 0 };
+ assertEquals(true, ArrayUtils.contains(array, (float) 0));
+ assertEquals(true, ArrayUtils.contains(array, (float) 1));
+ assertEquals(true, ArrayUtils.contains(array, (float) 2));
+ assertEquals(true, ArrayUtils.contains(array, (float) 3));
+ assertEquals(false, ArrayUtils.contains(array, (float) 99));
+ }
+
+ //-----------------------------------------------------------------------
+ public void testIndexOfBoolean() {
+ boolean[] array = null;
+ assertEquals(-1, ArrayUtils.indexOf(array, true));
+ array = new boolean[0];
+ assertEquals(-1, ArrayUtils.indexOf(array, true));
+ array = new boolean[] { true, false, true };
+ assertEquals(0, ArrayUtils.indexOf(array, true));
+ assertEquals(1, ArrayUtils.indexOf(array, false));
+ array = new boolean[] { true, true };
+ assertEquals(-1, ArrayUtils.indexOf(array, false));
+ }
+
+ public void testIndexOfBooleanWithStartIndex() {
+ boolean[] array = null;
+ assertEquals(-1, ArrayUtils.indexOf(array, true, 2));
+ array = new boolean[0];
+ assertEquals(-1, ArrayUtils.indexOf(array, true, 2));
+ array = new boolean[] { true, false, true };
+ assertEquals(2, ArrayUtils.indexOf(array, true, 1));
+ assertEquals(-1, ArrayUtils.indexOf(array, false, 2));
+ assertEquals(1, ArrayUtils.indexOf(array, false, 0));
+ assertEquals(1, ArrayUtils.indexOf(array, false, -1));
+ array = new boolean[] { true, true };
+ assertEquals(-1, ArrayUtils.indexOf(array, false, 0));
+ assertEquals(-1, ArrayUtils.indexOf(array, false, -1));
+ }
+
+ public void testLastIndexOfBoolean() {
+ boolean[] array = null;
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, true));
+ array = new boolean[0];
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, true));
+ array = new boolean[] { true, false, true };
+ assertEquals(2, ArrayUtils.lastIndexOf(array, true));
+ assertEquals(1, ArrayUtils.lastIndexOf(array, false));
+ array = new boolean[] { true, true };
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, false));
+ }
+
+ public void testLastIndexOfBooleanWithStartIndex() {
+ boolean[] array = null;
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, true, 2));
+ array = new boolean[0];
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, true, 2));
+ array = new boolean[] { true, false, true };
+ assertEquals(2, ArrayUtils.lastIndexOf(array, true, 2));
+ assertEquals(0, ArrayUtils.lastIndexOf(array, true, 1));
+ assertEquals(1, ArrayUtils.lastIndexOf(array, false, 2));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, true, -1));
+ array = new boolean[] { true, true };
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, false, 2));
+ assertEquals(-1, ArrayUtils.lastIndexOf(array, true, -1));
+ }
+
+ public void testContainsBoolean() {
+ boolean[] array = null;
+ assertEquals(false, ArrayUtils.contains(array, true));
+ array = new boolean[] { true, false, true };
+ assertEquals(true, ArrayUtils.contains(array, true));
+ assertEquals(true, ArrayUtils.contains(array, false));
+ array = new boolean[] { true, true };
+ assertEquals(true, ArrayUtils.contains(array, true));
+ assertEquals(false, ArrayUtils.contains(array, false));
+ }
+
+ // testToPrimitive/Object for boolean
+ // -----------------------------------------------------------------------
+ public void testToPrimitive_boolean() {
+ final Boolean[] b = null;
+ assertEquals(null, ArrayUtils.toPrimitive(b));
+ assertSame(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.toPrimitive(new Boolean[0]));
+ assertTrue(Arrays.equals(
+ new boolean[] {true, false, true},
+ ArrayUtils.toPrimitive(new Boolean[] {Boolean.TRUE, Boolean.FALSE, Boolean.TRUE}))
+ );
+
+ try {
+ ArrayUtils.toPrimitive(new Boolean[] {Boolean.TRUE, null});
+ fail();
+ } catch (NullPointerException ex) {}
+ }
+
+ public void testToPrimitive_boolean_boolean() {
+ assertEquals(null, ArrayUtils.toPrimitive(null, false));
+ assertSame(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.toPrimitive(new Boolean[0], false));
+ assertTrue(Arrays.equals(
+ new boolean[] {true, false, true},
+ ArrayUtils.toPrimitive(new Boolean[] {Boolean.TRUE, Boolean.FALSE, Boolean.TRUE}, false))
+ );
+ assertTrue(Arrays.equals(
+ new boolean[] {true, false, false},
+ ArrayUtils.toPrimitive(new Boolean[] {Boolean.TRUE, null, Boolean.FALSE}, false))
+ );
+ assertTrue(Arrays.equals(
+ new boolean[] {true, true, false},
+ ArrayUtils.toPrimitive(new Boolean[] {Boolean.TRUE, null, Boolean.FALSE}, true))
+ );
+ }
+
+ public void testToObject_boolean() {
+ final boolean[] b = null;
+ assertEquals(null, ArrayUtils.toObject(b));
+ assertSame(ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY, ArrayUtils.toObject(new boolean[0]));
+ assertTrue(Arrays.equals(
+ new Boolean[] {Boolean.TRUE, Boolean.FALSE, Boolean.TRUE},
+ ArrayUtils.toObject(new boolean[] {true, false, true}))
+ );
+ }
+
+ // testToPrimitive/Object for byte
+ // -----------------------------------------------------------------------
+ public void testToPrimitive_char() {
+ final Character[] b = null;
+ assertEquals(null, ArrayUtils.toPrimitive(b));
+
+ assertSame(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.toPrimitive(new Character[0]));
+
+ assertTrue(Arrays.equals(
+ new char[] {Character.MIN_VALUE, Character.MAX_VALUE, '0'},
+ ArrayUtils.toPrimitive(new Character[] {new Character(Character.MIN_VALUE),
+ new Character(Character.MAX_VALUE), new Character('0')}))
+ );
+
+ try {
+ ArrayUtils.toPrimitive(new Character[] {new Character(Character.MIN_VALUE), null});
+ fail();
+ } catch (NullPointerException ex) {}
+ }
+
+ public void testToPrimitive_char_char() {
+ final Character[] b = null;
+ assertEquals(null, ArrayUtils.toPrimitive(b, Character.MIN_VALUE));
+
+ assertSame(ArrayUtils.EMPTY_CHAR_ARRAY,
+ ArrayUtils.toPrimitive(new Character[0], (char)0));
+
+ assertTrue(Arrays.equals(
+ new char[] {Character.MIN_VALUE, Character.MAX_VALUE, '0'},
+ ArrayUtils.toPrimitive(new Character[] {new Character(Character.MIN_VALUE),
+ new Character(Character.MAX_VALUE), new Character('0')},
+ Character.MIN_VALUE))
+ );
+
+ assertTrue(Arrays.equals(
+ new char[] {Character.MIN_VALUE, Character.MAX_VALUE, '0'},
+ ArrayUtils.toPrimitive(new Character[] {new Character(Character.MIN_VALUE), null,
+ new Character('0')}, Character.MAX_VALUE))
+ );
+ }
+
+ public void testToObject_char() {
+ final char[] b = null;
+ assertEquals(null, ArrayUtils.toObject(b));
+
+ assertSame(ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY,
+ ArrayUtils.toObject(new char[0]));
+
+ assertTrue(Arrays.equals(
+ new Character[] {new Character(Character.MIN_VALUE),
+ new Character(Character.MAX_VALUE), new Character('0')},
+ ArrayUtils.toObject(new char[] {Character.MIN_VALUE, Character.MAX_VALUE,
+ '0'} ))
+ );
+ }
+
+ // testToPrimitive/Object for byte
+ // -----------------------------------------------------------------------
+ public void testToPrimitive_byte() {
+ final Byte[] b = null;
+ assertEquals(null, ArrayUtils.toPrimitive(b));
+
+ assertSame(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.toPrimitive(new Byte[0]));
+
+ assertTrue(Arrays.equals(
+ new byte[] {Byte.MIN_VALUE, Byte.MAX_VALUE, (byte)9999999},
+ ArrayUtils.toPrimitive(new Byte[] {Byte.valueOf(Byte.MIN_VALUE),
+ Byte.valueOf(Byte.MAX_VALUE), Byte.valueOf((byte)9999999)}))
+ );
+
+ try {
+ ArrayUtils.toPrimitive(new Byte[] {Byte.valueOf(Byte.MIN_VALUE), null});
+ fail();
+ } catch (NullPointerException ex) {}
+ }
+
+ public void testToPrimitive_byte_byte() {
+ final Byte[] b = null;
+ assertEquals(null, ArrayUtils.toPrimitive(b, Byte.MIN_VALUE));
+
+ assertSame(ArrayUtils.EMPTY_BYTE_ARRAY,
+ ArrayUtils.toPrimitive(new Byte[0], (byte)1));
+
+ assertTrue(Arrays.equals(
+ new byte[] {Byte.MIN_VALUE, Byte.MAX_VALUE, (byte)9999999},
+ ArrayUtils.toPrimitive(new Byte[] {Byte.valueOf(Byte.MIN_VALUE),
+ Byte.valueOf(Byte.MAX_VALUE), Byte.valueOf((byte)9999999)},
+ Byte.MIN_VALUE))
+ );
+
+ assertTrue(Arrays.equals(
+ new byte[] {Byte.MIN_VALUE, Byte.MAX_VALUE, (byte)9999999},
+ ArrayUtils.toPrimitive(new Byte[] {Byte.valueOf(Byte.MIN_VALUE), null,
+ Byte.valueOf((byte)9999999)}, Byte.MAX_VALUE))
+ );
+ }
+
+ public void testToObject_byte() {
+ final byte[] b = null;
+ assertEquals(null, ArrayUtils.toObject(b));
+
+ assertSame(ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY,
+ ArrayUtils.toObject(new byte[0]));
+
+ assertTrue(Arrays.equals(
+ new Byte[] {Byte.valueOf(Byte.MIN_VALUE),
+ Byte.valueOf(Byte.MAX_VALUE), Byte.valueOf((byte)9999999)},
+ ArrayUtils.toObject(new byte[] {Byte.MIN_VALUE, Byte.MAX_VALUE,
+ (byte)9999999}))
+ );
+ }
+
+ // testToPrimitive/Object for short
+ // -----------------------------------------------------------------------
+ public void testToPrimitive_short() {
+ final Short[] b = null;
+ assertEquals(null, ArrayUtils.toPrimitive(b));
+
+ assertSame(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.toPrimitive(new Short[0]));
+
+ assertTrue(Arrays.equals(
+ new short[] {Short.MIN_VALUE, Short.MAX_VALUE, (short)9999999},
+ ArrayUtils.toPrimitive(new Short[] {Short.valueOf(Short.MIN_VALUE),
+ Short.valueOf(Short.MAX_VALUE), Short.valueOf((short)9999999)}))
+ );
+
+ try {
+ ArrayUtils.toPrimitive(new Short[] {Short.valueOf(Short.MIN_VALUE), null});
+ fail();
+ } catch (NullPointerException ex) {}
+ }
+
+ public void testToPrimitive_short_short() {
+ final Short[] s = null;
+ assertEquals(null, ArrayUtils.toPrimitive(s, Short.MIN_VALUE));
+
+ assertSame(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.toPrimitive(new Short[0],
+ Short.MIN_VALUE));
+
+ assertTrue(Arrays.equals(
+ new short[] {Short.MIN_VALUE, Short.MAX_VALUE, (short)9999999},
+ ArrayUtils.toPrimitive(new Short[] {Short.valueOf(Short.MIN_VALUE),
+ Short.valueOf(Short.MAX_VALUE), Short.valueOf((short)9999999)}, Short.MIN_VALUE))
+ );
+
+ assertTrue(Arrays.equals(
+ new short[] {Short.MIN_VALUE, Short.MAX_VALUE, (short)9999999},
+ ArrayUtils.toPrimitive(new Short[] {Short.valueOf(Short.MIN_VALUE), null,
+ Short.valueOf((short)9999999)}, Short.MAX_VALUE))
+ );
+ }
+
+ public void testToObject_short() {
+ final short[] b = null;
+ assertEquals(null, ArrayUtils.toObject(b));
+
+ assertSame(ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY,
+ ArrayUtils.toObject(new short[0]));
+
+ assertTrue(Arrays.equals(
+ new Short[] {Short.valueOf(Short.MIN_VALUE), Short.valueOf(Short.MAX_VALUE),
+ Short.valueOf((short)9999999)},
+ ArrayUtils.toObject(new short[] {Short.MIN_VALUE, Short.MAX_VALUE,
+ (short)9999999}))
+ );
+ }
+
+ // testToPrimitive/Object for int
+ // -----------------------------------------------------------------------
+ public void testToPrimitive_int() {
+ final Integer[] b = null;
+ assertEquals(null, ArrayUtils.toPrimitive(b));
+ assertSame(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.toPrimitive(new Integer[0]));
+ assertTrue(Arrays.equals(
+ new int[] {Integer.MIN_VALUE, Integer.MAX_VALUE, 9999999},
+ ArrayUtils.toPrimitive(new Integer[] {Integer.valueOf(Integer.MIN_VALUE),
+ Integer.valueOf(Integer.MAX_VALUE), Integer.valueOf(9999999)}))
+ );
+
+ try {
+ ArrayUtils.toPrimitive(new Integer[] {Integer.valueOf(Integer.MIN_VALUE), null});
+ fail();
+ } catch (NullPointerException ex) {}
+ }
+
+ public void testToPrimitive_int_int() {
+ final Long[] l = null;
+ assertEquals(null, ArrayUtils.toPrimitive(l, Integer.MIN_VALUE));
+ assertSame(ArrayUtils.EMPTY_INT_ARRAY,
+ ArrayUtils.toPrimitive(new Integer[0], 1));
+ assertTrue(Arrays.equals(
+ new int[] {Integer.MIN_VALUE, Integer.MAX_VALUE, 9999999},
+ ArrayUtils.toPrimitive(new Integer[] {Integer.valueOf(Integer.MIN_VALUE),
+ Integer.valueOf(Integer.MAX_VALUE), Integer.valueOf(9999999)},1)));
+ assertTrue(Arrays.equals(
+ new int[] {Integer.MIN_VALUE, Integer.MAX_VALUE, 9999999},
+ ArrayUtils.toPrimitive(new Integer[] {Integer.valueOf(Integer.MIN_VALUE),
+ null, Integer.valueOf(9999999)}, Integer.MAX_VALUE))
+ );
+ }
+
+ public void testToPrimitive_intNull() {
+ Integer[] iArray = null;
+ assertEquals(null, ArrayUtils.toPrimitive(iArray, Integer.MIN_VALUE));
+ }
+
+ public void testToObject_int() {
+ final int[] b = null;
+ assertEquals(null, ArrayUtils.toObject(b));
+
+ assertSame(
+ ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY,
+ ArrayUtils.toObject(new int[0]));
+
+ assertTrue(
+ Arrays.equals(
+ new Integer[] {
+ Integer.valueOf(Integer.MIN_VALUE),
+ Integer.valueOf(Integer.MAX_VALUE),
+ Integer.valueOf(9999999)},
+ ArrayUtils.toObject(
+ new int[] { Integer.MIN_VALUE, Integer.MAX_VALUE, 9999999 })));
+ }
+
+ // testToPrimitive/Object for long
+ // -----------------------------------------------------------------------
+ public void testToPrimitive_long() {
+ final Long[] b = null;
+ assertEquals(null, ArrayUtils.toPrimitive(b));
+
+ assertSame(ArrayUtils.EMPTY_LONG_ARRAY,
+ ArrayUtils.toPrimitive(new Long[0]));
+
+ assertTrue(Arrays.equals(
+ new long[] {Long.MIN_VALUE, Long.MAX_VALUE, 9999999},
+ ArrayUtils.toPrimitive(new Long[] {Long.valueOf(Long.MIN_VALUE),
+ Long.valueOf(Long.MAX_VALUE), Long.valueOf(9999999)}))
+ );
+
+ try {
+ ArrayUtils.toPrimitive(new Long[] {Long.valueOf(Long.MIN_VALUE), null});
+ fail();
+ } catch (NullPointerException ex) {}
+ }
+
+ public void testToPrimitive_long_long() {
+ final Long[] l = null;
+ assertEquals(null, ArrayUtils.toPrimitive(l, Long.MIN_VALUE));
+
+ assertSame(ArrayUtils.EMPTY_LONG_ARRAY,
+ ArrayUtils.toPrimitive(new Long[0], 1));
+
+ assertTrue(Arrays.equals(
+ new long[] {Long.MIN_VALUE, Long.MAX_VALUE, 9999999},
+ ArrayUtils.toPrimitive(new Long[] {Long.valueOf(Long.MIN_VALUE),
+ Long.valueOf(Long.MAX_VALUE), Long.valueOf(9999999)},1)));
+
+ assertTrue(Arrays.equals(
+ new long[] {Long.MIN_VALUE, Long.MAX_VALUE, 9999999},
+ ArrayUtils.toPrimitive(new Long[] {Long.valueOf(Long.MIN_VALUE),
+ null, Long.valueOf(9999999)}, Long.MAX_VALUE))
+ );
+ }
+
+ public void testToObject_long() {
+ final long[] b = null;
+ assertEquals(null, ArrayUtils.toObject(b));
+
+ assertSame(
+ ArrayUtils.EMPTY_LONG_OBJECT_ARRAY,
+ ArrayUtils.toObject(new long[0]));
+
+ assertTrue(
+ Arrays.equals(
+ new Long[] {
+ Long.valueOf(Long.MIN_VALUE),
+ Long.valueOf(Long.MAX_VALUE),
+ Long.valueOf(9999999)},
+ ArrayUtils.toObject(
+ new long[] { Long.MIN_VALUE, Long.MAX_VALUE, 9999999 })));
+ }
+
+ // testToPrimitive/Object for float
+ // -----------------------------------------------------------------------
+ public void testToPrimitive_float() {
+ final Float[] b = null;
+ assertEquals(null, ArrayUtils.toPrimitive(b));
+
+ assertSame(ArrayUtils.EMPTY_FLOAT_ARRAY,
+ ArrayUtils.toPrimitive(new Float[0]));
+
+ assertTrue(Arrays.equals(
+ new float[] {Float.MIN_VALUE, Float.MAX_VALUE, 9999999},
+ ArrayUtils.toPrimitive(new Float[] {Float.valueOf(Float.MIN_VALUE),
+ Float.valueOf(Float.MAX_VALUE), Float.valueOf(9999999)}))
+ );
+
+ try {
+ ArrayUtils.toPrimitive(new Float[] {Float.valueOf(Float.MIN_VALUE), null});
+ fail();
+ } catch (NullPointerException ex) {}
+ }
+
+ public void testToPrimitive_float_float() {
+ final Float[] l = null;
+ assertEquals(null, ArrayUtils.toPrimitive(l, Float.MIN_VALUE));
+
+ assertSame(ArrayUtils.EMPTY_FLOAT_ARRAY,
+ ArrayUtils.toPrimitive(new Float[0], 1));
+
+ assertTrue(Arrays.equals(
+ new float[] {Float.MIN_VALUE, Float.MAX_VALUE, 9999999},
+ ArrayUtils.toPrimitive(new Float[] {Float.valueOf(Float.MIN_VALUE),
+ Float.valueOf(Float.MAX_VALUE), Float.valueOf(9999999)},1)));
+
+ assertTrue(Arrays.equals(
+ new float[] {Float.MIN_VALUE, Float.MAX_VALUE, 9999999},
+ ArrayUtils.toPrimitive(new Float[] {Float.valueOf(Float.MIN_VALUE),
+ null, Float.valueOf(9999999)}, Float.MAX_VALUE))
+ );
+ }
+
+ public void testToObject_float() {
+ final float[] b = null;
+ assertEquals(null, ArrayUtils.toObject(b));
+
+ assertSame(
+ ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY,
+ ArrayUtils.toObject(new float[0]));
+
+ assertTrue(
+ Arrays.equals(
+ new Float[] {
+ Float.valueOf(Float.MIN_VALUE),
+ Float.valueOf(Float.MAX_VALUE),
+ Float.valueOf(9999999)},
+ ArrayUtils.toObject(
+ new float[] { Float.MIN_VALUE, Float.MAX_VALUE, 9999999 })));
+ }
+
+ // testToPrimitive/Object for double
+ // -----------------------------------------------------------------------
+ public void testToPrimitive_double() {
+ final Double[] b = null;
+ assertEquals(null, ArrayUtils.toPrimitive(b));
+
+ assertSame(ArrayUtils.EMPTY_DOUBLE_ARRAY,
+ ArrayUtils.toPrimitive(new Double[0]));
+
+ assertTrue(Arrays.equals(
+ new double[] {Double.MIN_VALUE, Double.MAX_VALUE, 9999999},
+ ArrayUtils.toPrimitive(new Double[] {Double.valueOf(Double.MIN_VALUE),
+ Double.valueOf(Double.MAX_VALUE), Double.valueOf(9999999)}))
+ );
+
+ try {
+ ArrayUtils.toPrimitive(new Float[] {Float.valueOf(Float.MIN_VALUE), null});
+ fail();
+ } catch (NullPointerException ex) {}
+ }
+
+ public void testToPrimitive_double_double() {
+ final Double[] l = null;
+ assertEquals(null, ArrayUtils.toPrimitive(l, Double.MIN_VALUE));
+
+ assertSame(ArrayUtils.EMPTY_DOUBLE_ARRAY,
+ ArrayUtils.toPrimitive(new Double[0], 1));
+
+ assertTrue(Arrays.equals(
+ new double[] {Double.MIN_VALUE, Double.MAX_VALUE, 9999999},
+ ArrayUtils.toPrimitive(new Double[] {Double.valueOf(Double.MIN_VALUE),
+ Double.valueOf(Double.MAX_VALUE), Double.valueOf(9999999)},1)));
+
+ assertTrue(Arrays.equals(
+ new double[] {Double.MIN_VALUE, Double.MAX_VALUE, 9999999},
+ ArrayUtils.toPrimitive(new Double[] {Double.valueOf(Double.MIN_VALUE),
+ null, Double.valueOf(9999999)}, Double.MAX_VALUE))
+ );
+ }
+
+ public void testToObject_double() {
+ final double[] b = null;
+ assertEquals(null, ArrayUtils.toObject(b));
+
+ assertSame(
+ ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY,
+ ArrayUtils.toObject(new double[0]));
+
+ assertTrue(
+ Arrays.equals(
+ new Double[] {
+ Double.valueOf(Double.MIN_VALUE),
+ Double.valueOf(Double.MAX_VALUE),
+ Double.valueOf(9999999)},
+ ArrayUtils.toObject(
+ new double[] { Double.MIN_VALUE, Double.MAX_VALUE, 9999999 })));
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Test for {@link ArrayUtils#isEmpty(java.lang.Object[])}.
+ */
+ public void testIsEmptyObject() {
+ Object[] emptyArray = new Object[] {};
+ Object[] notEmptyArray = new Object[] { new String("Value") };
+ assertEquals(true, ArrayUtils.isEmpty((Object[])null));
+ assertEquals(true, ArrayUtils.isEmpty(emptyArray));
+ assertEquals(false, ArrayUtils.isEmpty(notEmptyArray));
+ }
+
+ /**
+ * Tests for {@link ArrayUtils#isEmpty(long[])},
+ * {@link ArrayUtils#isEmpty(int[])},
+ * {@link ArrayUtils#isEmpty(short[])},
+ * {@link ArrayUtils#isEmpty(char[])},
+ * {@link ArrayUtils#isEmpty(byte[])},
+ * {@link ArrayUtils#isEmpty(double[])},
+ * {@link ArrayUtils#isEmpty(float[])} and
+ * {@link ArrayUtils#isEmpty(boolean[])}.
+ */
+ public void testIsEmptyPrimitives() {
+ long[] emptyLongArray = new long[] {};
+ long[] notEmptyLongArray = new long[] { 1L };
+ assertEquals(true, ArrayUtils.isEmpty((long[])null));
+ assertEquals(true, ArrayUtils.isEmpty(emptyLongArray));
+ assertEquals(false, ArrayUtils.isEmpty(notEmptyLongArray));
+
+ int[] emptyIntArray = new int[] {};
+ int[] notEmptyIntArray = new int[] { 1 };
+ assertEquals(true, ArrayUtils.isEmpty((int[])null));
+ assertEquals(true, ArrayUtils.isEmpty(emptyIntArray));
+ assertEquals(false, ArrayUtils.isEmpty(notEmptyIntArray));
+
+ short[] emptyShortArray = new short[] {};
+ short[] notEmptyShortArray = new short[] { 1 };
+ assertEquals(true, ArrayUtils.isEmpty((short[])null));
+ assertEquals(true, ArrayUtils.isEmpty(emptyShortArray));
+ assertEquals(false, ArrayUtils.isEmpty(notEmptyShortArray));
+
+ char[] emptyCharArray = new char[] {};
+ char[] notEmptyCharArray = new char[] { 1 };
+ assertEquals(true, ArrayUtils.isEmpty((char[])null));
+ assertEquals(true, ArrayUtils.isEmpty(emptyCharArray));
+ assertEquals(false, ArrayUtils.isEmpty(notEmptyCharArray));
+
+ byte[] emptyByteArray = new byte[] {};
+ byte[] notEmptyByteArray = new byte[] { 1 };
+ assertEquals(true, ArrayUtils.isEmpty((byte[])null));
+ assertEquals(true, ArrayUtils.isEmpty(emptyByteArray));
+ assertEquals(false, ArrayUtils.isEmpty(notEmptyByteArray));
+
+ double[] emptyDoubleArray = new double[] {};
+ double[] notEmptyDoubleArray = new double[] { 1.0 };
+ assertEquals(true, ArrayUtils.isEmpty((double[])null));
+ assertEquals(true, ArrayUtils.isEmpty(emptyDoubleArray));
+ assertEquals(false, ArrayUtils.isEmpty(notEmptyDoubleArray));
+
+ float[] emptyFloatArray = new float[] {};
+ float[] notEmptyFloatArray = new float[] { 1.0F };
+ assertEquals(true, ArrayUtils.isEmpty((float[])null));
+ assertEquals(true, ArrayUtils.isEmpty(emptyFloatArray));
+ assertEquals(false, ArrayUtils.isEmpty(notEmptyFloatArray));
+
+ boolean[] emptyBooleanArray = new boolean[] {};
+ boolean[] notEmptyBooleanArray = new boolean[] { true };
+ assertEquals(true, ArrayUtils.isEmpty((boolean[])null));
+ assertEquals(true, ArrayUtils.isEmpty(emptyBooleanArray));
+ assertEquals(false, ArrayUtils.isEmpty(notEmptyBooleanArray));
+ }
+
+ /**
+ * Test for {@link ArrayUtils#isNotEmpty(java.lang.Object[])}.
+ */
+ public void testIsNotEmptyObject() {
+ Object[] emptyArray = new Object[] {};
+ Object[] notEmptyArray = new Object[] { new String("Value") };
+ assertFalse(ArrayUtils.isNotEmpty((Object[])null));
+ assertFalse(ArrayUtils.isNotEmpty(emptyArray));
+ assertTrue(ArrayUtils.isNotEmpty(notEmptyArray));
+ }
+
+ /**
+ * Tests for {@link ArrayUtils#isNotEmpty(long[])},
+ * {@link ArrayUtils#isNotEmpty(int[])},
+ * {@link ArrayUtils#isNotEmpty(short[])},
+ * {@link ArrayUtils#isNotEmpty(char[])},
+ * {@link ArrayUtils#isNotEmpty(byte[])},
+ * {@link ArrayUtils#isNotEmpty(double[])},
+ * {@link ArrayUtils#isNotEmpty(float[])} and
+ * {@link ArrayUtils#isNotEmpty(boolean[])}.
+ */
+ public void testIsNotEmptyPrimitives() {
+ long[] emptyLongArray = new long[] {};
+ long[] notEmptyLongArray = new long[] { 1L };
+ assertFalse(ArrayUtils.isNotEmpty((long[])null));
+ assertFalse(ArrayUtils.isNotEmpty(emptyLongArray));
+ assertTrue(ArrayUtils.isNotEmpty(notEmptyLongArray));
+
+ int[] emptyIntArray = new int[] {};
+ int[] notEmptyIntArray = new int[] { 1 };
+ assertFalse(ArrayUtils.isNotEmpty((int[])null));
+ assertFalse(ArrayUtils.isNotEmpty(emptyIntArray));
+ assertTrue(ArrayUtils.isNotEmpty(notEmptyIntArray));
+
+ short[] emptyShortArray = new short[] {};
+ short[] notEmptyShortArray = new short[] { 1 };
+ assertFalse(ArrayUtils.isNotEmpty((short[])null));
+ assertFalse(ArrayUtils.isNotEmpty(emptyShortArray));
+ assertTrue(ArrayUtils.isNotEmpty(notEmptyShortArray));
+
+ char[] emptyCharArray = new char[] {};
+ char[] notEmptyCharArray = new char[] { 1 };
+ assertFalse(ArrayUtils.isNotEmpty((char[])null));
+ assertFalse(ArrayUtils.isNotEmpty(emptyCharArray));
+ assertTrue(ArrayUtils.isNotEmpty(notEmptyCharArray));
+
+ byte[] emptyByteArray = new byte[] {};
+ byte[] notEmptyByteArray = new byte[] { 1 };
+ assertFalse(ArrayUtils.isNotEmpty((byte[])null));
+ assertFalse(ArrayUtils.isNotEmpty(emptyByteArray));
+ assertTrue(ArrayUtils.isNotEmpty(notEmptyByteArray));
+
+ double[] emptyDoubleArray = new double[] {};
+ double[] notEmptyDoubleArray = new double[] { 1.0 };
+ assertFalse(ArrayUtils.isNotEmpty((double[])null));
+ assertFalse(ArrayUtils.isNotEmpty(emptyDoubleArray));
+ assertTrue(ArrayUtils.isNotEmpty(notEmptyDoubleArray));
+
+ float[] emptyFloatArray = new float[] {};
+ float[] notEmptyFloatArray = new float[] { 1.0F };
+ assertFalse(ArrayUtils.isNotEmpty((float[])null));
+ assertFalse(ArrayUtils.isNotEmpty(emptyFloatArray));
+ assertTrue(ArrayUtils.isNotEmpty(notEmptyFloatArray));
+
+ boolean[] emptyBooleanArray = new boolean[] {};
+ boolean[] notEmptyBooleanArray = new boolean[] { true };
+ assertFalse(ArrayUtils.isNotEmpty((boolean[])null));
+ assertFalse(ArrayUtils.isNotEmpty(emptyBooleanArray));
+ assertTrue(ArrayUtils.isNotEmpty(notEmptyBooleanArray));
+ }
+ // ------------------------------------------------------------------------
+ public void testGetLength() {
+ assertEquals(0, ArrayUtils.getLength(null));
+
+ Object[] emptyObjectArray = new Object[0];
+ Object[] notEmptyObjectArray = new Object[] {"aValue"};
+ assertEquals(0, ArrayUtils.getLength((Object[]) null));
+ assertEquals(0, ArrayUtils.getLength(emptyObjectArray));
+ assertEquals(1, ArrayUtils.getLength(notEmptyObjectArray));
+
+ int[] emptyIntArray = new int[] {};
+ int[] notEmptyIntArray = new int[] { 1 };
+ assertEquals(0, ArrayUtils.getLength((int[]) null));
+ assertEquals(0, ArrayUtils.getLength(emptyIntArray));
+ assertEquals(1, ArrayUtils.getLength(notEmptyIntArray));
+
+ short[] emptyShortArray = new short[] {};
+ short[] notEmptyShortArray = new short[] { 1 };
+ assertEquals(0, ArrayUtils.getLength((short[]) null));
+ assertEquals(0, ArrayUtils.getLength(emptyShortArray));
+ assertEquals(1, ArrayUtils.getLength(notEmptyShortArray));
+
+ char[] emptyCharArray = new char[] {};
+ char[] notEmptyCharArray = new char[] { 1 };
+ assertEquals(0, ArrayUtils.getLength((char[]) null));
+ assertEquals(0, ArrayUtils.getLength(emptyCharArray));
+ assertEquals(1, ArrayUtils.getLength(notEmptyCharArray));
+
+ byte[] emptyByteArray = new byte[] {};
+ byte[] notEmptyByteArray = new byte[] { 1 };
+ assertEquals(0, ArrayUtils.getLength((byte[]) null));
+ assertEquals(0, ArrayUtils.getLength(emptyByteArray));
+ assertEquals(1, ArrayUtils.getLength(notEmptyByteArray));
+
+ double[] emptyDoubleArray = new double[] {};
+ double[] notEmptyDoubleArray = new double[] { 1.0 };
+ assertEquals(0, ArrayUtils.getLength((double[]) null));
+ assertEquals(0, ArrayUtils.getLength(emptyDoubleArray));
+ assertEquals(1, ArrayUtils.getLength(notEmptyDoubleArray));
+
+ float[] emptyFloatArray = new float[] {};
+ float[] notEmptyFloatArray = new float[] { 1.0F };
+ assertEquals(0, ArrayUtils.getLength((float[]) null));
+ assertEquals(0, ArrayUtils.getLength(emptyFloatArray));
+ assertEquals(1, ArrayUtils.getLength(notEmptyFloatArray));
+
+ boolean[] emptyBooleanArray = new boolean[] {};
+ boolean[] notEmptyBooleanArray = new boolean[] { true };
+ assertEquals(0, ArrayUtils.getLength((boolean[]) null));
+ assertEquals(0, ArrayUtils.getLength(emptyBooleanArray));
+ assertEquals(1, ArrayUtils.getLength(notEmptyBooleanArray));
+
+ try {
+ ArrayUtils.getLength("notAnArray");
+ fail("IllegalArgumentException should have been thrown");
+ } catch (IllegalArgumentException e) {}
+ }
+
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/BitField.java b/ApacheCommonsLang/org/apache/commons/lang3/BitField.java
new file mode 100644
index 0000000..f8d936d
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/BitField.java
@@ -0,0 +1,283 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+package org.apache.commons.lang3;
+
+/**
+ * Operations on bit-mapped fields.
+ *
+ * @since 2.0
+ * @version $Id: BitField.java 1088899 2011-04-05 05:31:27Z bayard $
+ */
+public class BitField {
+
+ private final int _mask;
+ private final int _shift_count;
+
+ /**
+ * Creates a BitField instance.
+ *
+ * @param mask the mask specifying which bits apply to this
+ * BitField. Bits that are set in this mask are the bits
+ * that this BitField operates on
+ */
+ public BitField(int mask) {
+ _mask = mask;
+ int count = 0;
+ int bit_pattern = mask;
+
+ if (bit_pattern != 0) {
+ while ((bit_pattern & 1) == 0) {
+ count++;
+ bit_pattern >>= 1;
+ }
+ }
+ _shift_count = count;
+ }
+
+ /**
+ * Obtains the value for the specified BitField, appropriately
+ * shifted right.
+ *
+ * Many users of a BitField will want to treat the specified
+ * bits as an int value, and will not want to be aware that the
+ * value is stored as a BitField (and so shifted left so many
+ * bits).
+ *
+ * @see #setValue(int,int)
+ * @param holder the int data containing the bits we're interested
+ * in
+ * @return the selected bits, shifted right appropriately
+ */
+ public int getValue(int holder) {
+ return getRawValue(holder) >> _shift_count;
+ }
+
+ /**
+ * Obtains the value for the specified BitField, appropriately
+ * shifted right, as a short.
+ *
+ * Many users of a BitField will want to treat the specified
+ * bits as an int value, and will not want to be aware that the
+ * value is stored as a BitField (and so shifted left so many
+ * bits).
+ *
+ * @see #setShortValue(short,short)
+ * @param holder the short data containing the bits we're
+ * interested in
+ * @return the selected bits, shifted right appropriately
+ */
+ public short getShortValue(short holder) {
+ return (short) getValue(holder);
+ }
+
+ /**
+ * Obtains the value for the specified BitField, unshifted.
+ *
+ * @param holder the int data containing the bits we're
+ * interested in
+ * @return the selected bits
+ */
+ public int getRawValue(int holder) {
+ return holder & _mask;
+ }
+
+ /**
+ * Obtains the value for the specified BitField, unshifted.
+ *
+ * @param holder the short data containing the bits we're
+ * interested in
+ * @return the selected bits
+ */
+ public short getShortRawValue(short holder) {
+ return (short) getRawValue(holder);
+ }
+
+ /**
+ * Returns whether the field is set or not.
+ *
+ * This is most commonly used for a single-bit field, which is
+ * often used to represent a boolean value; the results of using
+ * it for a multi-bit field is to determine whether *any* of its
+ * bits are set.
+ *
+ * @param holder the int data containing the bits we're interested
+ * in
+ * @return {@code true} if any of the bits are set,
+ * else {@code false}
+ */
+ public boolean isSet(int holder) {
+ return (holder & _mask) != 0;
+ }
+
+ /**
+ * Returns whether all of the bits are set or not.
+ *
+ * This is a stricter test than {@link #isSet(int)},
+ * in that all of the bits in a multi-bit set must be set
+ * for this method to return {@code true}.
+ *
+ * @param holder the int data containing the bits we're
+ * interested in
+ * @return {@code true} if all of the bits are set,
+ * else {@code false}
+ */
+ public boolean isAllSet(int holder) {
+ return (holder & _mask) == _mask;
+ }
+
+ /**
+ * Replaces the bits with new values.
+ *
+ * @see #getValue(int)
+ * @param holder the int data containing the bits we're
+ * interested in
+ * @param value the new value for the specified bits
+ * @return the value of holder with the bits from the value
+ * parameter replacing the old bits
+ */
+ public int setValue(int holder, int value) {
+ return (holder & ~_mask) | ((value << _shift_count) & _mask);
+ }
+
+ /**
+ * Replaces the bits with new values.
+ *
+ * @see #getShortValue(short)
+ * @param holder the short data containing the bits we're
+ * interested in
+ * @param value the new value for the specified bits
+ * @return the value of holder with the bits from the value
+ * parameter replacing the old bits
+ */
+ public short setShortValue(short holder, short value) {
+ return (short) setValue(holder, value);
+ }
+
+ /**
+ * Clears the bits.
+ *
+ * @param holder the int data containing the bits we're
+ * interested in
+ * @return the value of holder with the specified bits cleared
+ * (set to {@code 0})
+ */
+ public int clear(int holder) {
+ return holder & ~_mask;
+ }
+
+ /**
+ * Clears the bits.
+ *
+ * @param holder the short data containing the bits we're
+ * interested in
+ * @return the value of holder with the specified bits cleared
+ * (set to {@code 0})
+ */
+ public short clearShort(short holder) {
+ return (short) clear(holder);
+ }
+
+ /**
+ * Clears the bits.
+ *
+ * @param holder the byte data containing the bits we're
+ * interested in
+ *
+ * @return the value of holder with the specified bits cleared
+ * (set to {@code 0})
+ */
+ public byte clearByte(byte holder) {
+ return (byte) clear(holder);
+ }
+
+ /**
+ * Sets the bits.
+ *
+ * @param holder the int data containing the bits we're
+ * interested in
+ * @return the value of holder with the specified bits set
+ * to {@code 1}
+ */
+ public int set(int holder) {
+ return holder | _mask;
+ }
+
+ /**
+ * Sets the bits.
+ *
+ * @param holder the short data containing the bits we're
+ * interested in
+ * @return the value of holder with the specified bits set
+ * to {@code 1}
+ */
+ public short setShort(short holder) {
+ return (short) set(holder);
+ }
+
+ /**
+ * Sets the bits.
+ *
+ * @param holder the byte data containing the bits we're
+ * interested in
+ *
+ * @return the value of holder with the specified bits set
+ * to {@code 1}
+ */
+ public byte setByte(byte holder) {
+ return (byte) set(holder);
+ }
+
+ /**
+ * Sets a boolean BitField.
+ *
+ * @param holder the int data containing the bits we're
+ * interested in
+ * @param flag indicating whether to set or clear the bits
+ * @return the value of holder with the specified bits set or
+ * cleared
+ */
+ public int setBoolean(int holder, boolean flag) {
+ return flag ? set(holder) : clear(holder);
+ }
+
+ /**
+ * Sets a boolean BitField.
+ *
+ * @param holder the short data containing the bits we're
+ * interested in
+ * @param flag indicating whether to set or clear the bits
+ * @return the value of holder with the specified bits set or
+ * cleared
+ */
+ public short setShortBoolean(short holder, boolean flag) {
+ return flag ? setShort(holder) : clearShort(holder);
+ }
+
+ /**
+ * Sets a boolean BitField.
+ *
+ * @param holder the byte data containing the bits we're
+ * interested in
+ * @param flag indicating whether to set or clear the bits
+ * @return the value of holder with the specified bits set or
+ * cleared
+ */
+ public byte setByteBoolean(byte holder, boolean flag) {
+ return flag ? setByte(holder) : clearByte(holder);
+ }
+
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/BitFieldTest.java b/ApacheCommonsLang/org/apache/commons/lang3/BitFieldTest.java
new file mode 100644
index 0000000..c276894
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/BitFieldTest.java
@@ -0,0 +1,251 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+package org.apache.commons.lang3;
+
+import junit.framework.TestCase;
+
+/**
+ * Class to test BitField functionality
+ *
+ * @version $Id: BitFieldTest.java 1199894 2011-11-09 17:53:59Z ggregory $
+ */
+public class BitFieldTest extends TestCase {
+
+ private static final BitField bf_multi = new BitField(0x3F80);
+ private static final BitField bf_single = new BitField(0x4000);
+ private static final BitField bf_zero = new BitField(0);
+
+ /**
+ * Constructor BitFieldTest
+ *
+ * @param name
+ */
+ public BitFieldTest(String name) {
+ super(name);
+ }
+
+ /**
+ * test the getValue() method
+ */
+ public void testGetValue() {
+ assertEquals(bf_multi.getValue(-1), 127);
+ assertEquals(bf_multi.getValue(0), 0);
+ assertEquals(bf_single.getValue(-1), 1);
+ assertEquals(bf_single.getValue(0), 0);
+ assertEquals(bf_zero.getValue(-1), 0);
+ assertEquals(bf_zero.getValue(0), 0);
+ }
+
+ /**
+ * test the getShortValue() method
+ */
+ public void testGetShortValue() {
+ assertEquals(bf_multi.getShortValue((short) - 1), (short) 127);
+ assertEquals(bf_multi.getShortValue((short) 0), (short) 0);
+ assertEquals(bf_single.getShortValue((short) - 1), (short) 1);
+ assertEquals(bf_single.getShortValue((short) 0), (short) 0);
+ assertEquals(bf_zero.getShortValue((short) -1), (short) 0);
+ assertEquals(bf_zero.getShortValue((short) 0), (short) 0);
+ }
+
+ /**
+ * test the getRawValue() method
+ */
+ public void testGetRawValue() {
+ assertEquals(bf_multi.getRawValue(-1), 0x3F80);
+ assertEquals(bf_multi.getRawValue(0), 0);
+ assertEquals(bf_single.getRawValue(-1), 0x4000);
+ assertEquals(bf_single.getRawValue(0), 0);
+ assertEquals(bf_zero.getRawValue(-1), 0);
+ assertEquals(bf_zero.getRawValue(0), 0);
+ }
+
+ /**
+ * test the getShortRawValue() method
+ */
+ public void testGetShortRawValue() {
+ assertEquals(bf_multi.getShortRawValue((short) - 1), (short) 0x3F80);
+ assertEquals(bf_multi.getShortRawValue((short) 0), (short) 0);
+ assertEquals(bf_single.getShortRawValue((short) - 1), (short) 0x4000);
+ assertEquals(bf_single.getShortRawValue((short) 0), (short) 0);
+ assertEquals(bf_zero.getShortRawValue((short) -1), (short) 0);
+ assertEquals(bf_zero.getShortRawValue((short) 0), (short) 0);
+ }
+
+ /**
+ * test the isSet() method
+ */
+ public void testIsSet() {
+ assertTrue(!bf_multi.isSet(0));
+ assertTrue(!bf_zero.isSet(0));
+ for (int j = 0x80; j <= 0x3F80; j += 0x80) {
+ assertTrue(bf_multi.isSet(j));
+ }
+ for (int j = 0x80; j <= 0x3F80; j += 0x80) {
+ assertTrue(!bf_zero.isSet(j));
+ }
+ assertTrue(!bf_single.isSet(0));
+ assertTrue(bf_single.isSet(0x4000));
+ }
+
+ /**
+ * test the isAllSet() method
+ */
+ public void testIsAllSet() {
+ for (int j = 0; j < 0x3F80; j += 0x80) {
+ assertTrue(!bf_multi.isAllSet(j));
+ assertTrue(bf_zero.isAllSet(j));
+ }
+ assertTrue(bf_multi.isAllSet(0x3F80));
+ assertTrue(!bf_single.isAllSet(0));
+ assertTrue(bf_single.isAllSet(0x4000));
+ }
+
+ /**
+ * test the setValue() method
+ */
+ public void testSetValue() {
+ for (int j = 0; j < 128; j++) {
+ assertEquals(bf_multi.getValue(bf_multi.setValue(0, j)), j);
+ assertEquals(bf_multi.setValue(0, j), j << 7);
+ }
+ for (int j = 0; j < 128; j++) {
+ assertEquals(bf_zero.getValue(bf_zero.setValue(0, j)), 0);
+ assertEquals(bf_zero.setValue(0, j), 0);
+ }
+
+ // verify that excess bits are stripped off
+ assertEquals(bf_multi.setValue(0x3f80, 128), 0);
+ for (int j = 0; j < 2; j++) {
+ assertEquals(bf_single.getValue(bf_single.setValue(0, j)), j);
+ assertEquals(bf_single.setValue(0, j), j << 14);
+ }
+
+ // verify that excess bits are stripped off
+ assertEquals(bf_single.setValue(0x4000, 2), 0);
+ }
+
+ /**
+ * test the setShortValue() method
+ */
+ public void testSetShortValue() {
+ for (int j = 0; j < 128; j++) {
+ assertEquals(bf_multi.getShortValue(bf_multi.setShortValue((short) 0, (short) j)), (short) j);
+ assertEquals(bf_multi.setShortValue((short) 0, (short) j), (short) (j << 7));
+ }
+ for (int j = 0; j < 128; j++) {
+ assertEquals(bf_zero.getShortValue(bf_zero.setShortValue((short) 0, (short) j)), (short) 0);
+ assertEquals(bf_zero.setShortValue((short) 0, (short) j), (short) 0);
+ }
+
+ // verify that excess bits are stripped off
+ assertEquals(bf_multi.setShortValue((short) 0x3f80, (short) 128), (short) 0);
+ for (int j = 0; j < 2; j++) {
+ assertEquals(bf_single.getShortValue(bf_single.setShortValue((short) 0, (short) j)), (short) j);
+ assertEquals(bf_single.setShortValue((short) 0, (short) j), (short) (j << 14));
+ }
+
+ // verify that excess bits are stripped off
+ assertEquals(bf_single.setShortValue((short) 0x4000, (short) 2), (short) 0);
+ }
+
+ public void testByte() {
+ assertEquals(0, new BitField(0).setByteBoolean((byte) 0, true));
+ assertEquals(1, new BitField(1).setByteBoolean((byte) 0, true));
+ assertEquals(2, new BitField(2).setByteBoolean((byte) 0, true));
+ assertEquals(4, new BitField(4).setByteBoolean((byte) 0, true));
+ assertEquals(8, new BitField(8).setByteBoolean((byte) 0, true));
+ assertEquals(16, new BitField(16).setByteBoolean((byte) 0, true));
+ assertEquals(32, new BitField(32).setByteBoolean((byte) 0, true));
+ assertEquals(64, new BitField(64).setByteBoolean((byte) 0, true));
+ assertEquals(-128, new BitField(128).setByteBoolean((byte) 0, true));
+ assertEquals(1, new BitField(0).setByteBoolean((byte) 1, false));
+ assertEquals(0, new BitField(1).setByteBoolean((byte) 1, false));
+ assertEquals(0, new BitField(2).setByteBoolean((byte) 2, false));
+ assertEquals(0, new BitField(4).setByteBoolean((byte) 4, false));
+ assertEquals(0, new BitField(8).setByteBoolean((byte) 8, false));
+ assertEquals(0, new BitField(16).setByteBoolean((byte) 16, false));
+ assertEquals(0, new BitField(32).setByteBoolean((byte) 32, false));
+ assertEquals(0, new BitField(64).setByteBoolean((byte) 64, false));
+ assertEquals(0, new BitField(128).setByteBoolean((byte) 128, false));
+ assertEquals(-2, new BitField(1).setByteBoolean((byte) 255, false));
+ byte clearedBit = new BitField(0x40).setByteBoolean((byte) - 63, false);
+
+ assertEquals(false, new BitField(0x40).isSet(clearedBit));
+ }
+
+ /**
+ * test the clear() method
+ */
+ public void testClear() {
+ assertEquals(bf_multi.clear(-1), 0xFFFFC07F);
+ assertEquals(bf_single.clear(-1), 0xFFFFBFFF);
+ assertEquals(bf_zero.clear(-1), 0xFFFFFFFF);
+ }
+
+ /**
+ * test the clearShort() method
+ */
+ public void testClearShort() {
+ assertEquals(bf_multi.clearShort((short) - 1), (short) 0xC07F);
+ assertEquals(bf_single.clearShort((short) - 1), (short) 0xBFFF);
+ assertEquals(bf_zero.clearShort((short) -1), (short) 0xFFFF);
+ }
+
+ /**
+ * test the set() method
+ */
+ public void testSet() {
+ assertEquals(bf_multi.set(0), 0x3F80);
+ assertEquals(bf_single.set(0), 0x4000);
+ assertEquals(bf_zero.set(0), 0);
+ }
+
+ /**
+ * test the setShort() method
+ */
+ public void testSetShort() {
+ assertEquals(bf_multi.setShort((short) 0), (short) 0x3F80);
+ assertEquals(bf_single.setShort((short) 0), (short) 0x4000);
+ assertEquals(bf_zero.setShort((short) 0), (short) 0);
+ }
+
+ /**
+ * test the setBoolean() method
+ */
+ public void testSetBoolean() {
+ assertEquals(bf_multi.set(0), bf_multi.setBoolean(0, true));
+ assertEquals(bf_single.set(0), bf_single.setBoolean(0, true));
+ assertEquals(bf_zero.set(0), bf_zero.setBoolean(0, true));
+ assertEquals(bf_multi.clear(-1), bf_multi.setBoolean(-1, false));
+ assertEquals(bf_single.clear(-1), bf_single.setBoolean(-1, false));
+ assertEquals(bf_zero.clear(-1), bf_zero.setBoolean(-1, false));
+ }
+
+ /**
+ * test the setShortBoolean() method
+ */
+ public void testSetShortBoolean() {
+ assertEquals(bf_multi.setShort((short) 0), bf_multi.setShortBoolean((short) 0, true));
+ assertEquals(bf_single.setShort((short) 0), bf_single.setShortBoolean((short) 0, true));
+ assertEquals(bf_zero.setShort((short) 0), bf_zero.setShortBoolean((short) 0, true));
+ assertEquals(bf_multi.clearShort((short) - 1), bf_multi.setShortBoolean((short) - 1, false));
+ assertEquals(bf_single.clearShort((short) - 1), bf_single.setShortBoolean((short) - 1, false));
+ assertEquals(bf_zero.clearShort((short) -1), bf_zero.setShortBoolean((short) -1, false));
+ }
+
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/BooleanUtils.java b/ApacheCommonsLang/org/apache/commons/lang3/BooleanUtils.java
new file mode 100644
index 0000000..8244475
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/BooleanUtils.java
@@ -0,0 +1,1082 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+package org.apache.commons.lang3;
+
+import org.apache.commons.lang3.math.NumberUtils;
+
+/**
+ * Operations on boolean primitives and Boolean objects.
+ *
+ * This class tries to handle {@code null} input gracefully.
+ * An exception will not be thrown for a {@code null} input.
+ * Each method documents its behaviour in more detail.
+ *
+ * #ThreadSafe#
+ * @since 2.0
+ * @version $Id: BooleanUtils.java 1199894 2011-11-09 17:53:59Z ggregory $
+ */
+public class BooleanUtils {
+
+ /**
+ * {@code BooleanUtils} instances should NOT be constructed in standard programming.
+ * Instead, the class should be used as {@code BooleanUtils.negate(true);}.
+ *
+ * This constructor is public to permit tools that require a JavaBean instance
+ * to operate.
+ */
+ public BooleanUtils() {
+ super();
+ }
+
+ // Boolean utilities
+ //--------------------------------------------------------------------------
+ /**
+ * Negates the specified boolean.
+ *
+ * If {@code null} is passed in, {@code null} will be returned.
+ *
+ * NOTE: This returns null and will throw a NullPointerException if autoboxed to a boolean.
+ *
+ *
+ * BooleanUtils.negate(Boolean.TRUE) = Boolean.FALSE;
+ * BooleanUtils.negate(Boolean.FALSE) = Boolean.TRUE;
+ * BooleanUtils.negate(null) = null;
+ *
+ *
+ * @param bool the Boolean to negate, may be null
+ * @return the negated Boolean, or {@code null} if {@code null} input
+ */
+ public static Boolean negate(Boolean bool) {
+ if (bool == null) {
+ return null;
+ }
+ return bool.booleanValue() ? Boolean.FALSE : Boolean.TRUE;
+ }
+
+ // boolean Boolean methods
+ //-----------------------------------------------------------------------
+ /**
+ * Checks if a {@code Boolean} value is {@code true},
+ * handling {@code null} by returning {@code false}.
+ *
+ *
+ * BooleanUtils.isTrue(Boolean.TRUE) = true
+ * BooleanUtils.isTrue(Boolean.FALSE) = false
+ * BooleanUtils.isTrue(null) = false
+ *
+ *
+ * @param bool the boolean to check, null returns {@code false}
+ * @return {@code true} only if the input is non-null and true
+ * @since 2.1
+ */
+ public static boolean isTrue(Boolean bool) {
+ return Boolean.TRUE.equals(bool);
+ }
+
+ /**
+ * Checks if a {@code Boolean} value is not {@code true},
+ * handling {@code null} by returning {@code true}.
+ *
+ *
+ * BooleanUtils.isNotTrue(Boolean.TRUE) = false
+ * BooleanUtils.isNotTrue(Boolean.FALSE) = true
+ * BooleanUtils.isNotTrue(null) = true
+ *
+ *
+ * @param bool the boolean to check, null returns {@code true}
+ * @return {@code true} if the input is null or false
+ * @since 2.3
+ */
+ public static boolean isNotTrue(Boolean bool) {
+ return !isTrue(bool);
+ }
+
+ /**
+ * Checks if a {@code Boolean} value is {@code false},
+ * handling {@code null} by returning {@code false}.
+ *
+ *
+ * BooleanUtils.isFalse(Boolean.TRUE) = false
+ * BooleanUtils.isFalse(Boolean.FALSE) = true
+ * BooleanUtils.isFalse(null) = false
+ *
+ *
+ * @param bool the boolean to check, null returns {@code false}
+ * @return {@code true} only if the input is non-null and false
+ * @since 2.1
+ */
+ public static boolean isFalse(Boolean bool) {
+ return Boolean.FALSE.equals(bool);
+ }
+
+ /**
+ * Checks if a {@code Boolean} value is not {@code false},
+ * handling {@code null} by returning {@code true}.
+ *
+ *
+ * BooleanUtils.isNotFalse(Boolean.TRUE) = true
+ * BooleanUtils.isNotFalse(Boolean.FALSE) = false
+ * BooleanUtils.isNotFalse(null) = true
+ *
+ *
+ * @param bool the boolean to check, null returns {@code true}
+ * @return {@code true} if the input is null or true
+ * @since 2.3
+ */
+ public static boolean isNotFalse(Boolean bool) {
+ return !isFalse(bool);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Converts a Boolean to a boolean handling {@code null}
+ * by returning {@code false}.
+ *
+ *
+ * BooleanUtils.toBoolean(Boolean.TRUE) = true
+ * BooleanUtils.toBoolean(Boolean.FALSE) = false
+ * BooleanUtils.toBoolean(null) = false
+ *
+ *
+ * @param bool the boolean to convert
+ * @return {@code true} or {@code false}, {@code null} returns {@code false}
+ */
+ public static boolean toBoolean(Boolean bool) {
+ return bool != null && bool.booleanValue();
+ }
+
+ /**
+ * Converts a Boolean to a boolean handling {@code null}.
+ *
+ *
+ * BooleanUtils.toBooleanDefaultIfNull(Boolean.TRUE, false) = true
+ * BooleanUtils.toBooleanDefaultIfNull(Boolean.FALSE, true) = false
+ * BooleanUtils.toBooleanDefaultIfNull(null, true) = true
+ *
+ *
+ * @param bool the boolean to convert
+ * @param valueIfNull the boolean value to return if {@code null}
+ * @return {@code true} or {@code false}
+ */
+ public static boolean toBooleanDefaultIfNull(Boolean bool, boolean valueIfNull) {
+ if (bool == null) {
+ return valueIfNull;
+ }
+ return bool.booleanValue();
+ }
+
+ // Integer to Boolean methods
+ //-----------------------------------------------------------------------
+ /**
+ * Converts an int to a boolean using the convention that {@code zero}
+ * is {@code false}.
+ *
+ *
+ * BooleanUtils.toBoolean(0) = false
+ * BooleanUtils.toBoolean(1) = true
+ * BooleanUtils.toBoolean(2) = true
+ *
+ *
+ * @param value the int to convert
+ * @return {@code true} if non-zero, {@code false}
+ * if zero
+ */
+ public static boolean toBoolean(int value) {
+ return value != 0;
+ }
+
+ /**
+ * Converts an int to a Boolean using the convention that {@code zero}
+ * is {@code false}.
+ *
+ *
+ * BooleanUtils.toBoolean(0) = Boolean.FALSE
+ * BooleanUtils.toBoolean(1) = Boolean.TRUE
+ * BooleanUtils.toBoolean(2) = Boolean.TRUE
+ *
+ *
+ * @param value the int to convert
+ * @return Boolean.TRUE if non-zero, Boolean.FALSE if zero,
+ * {@code null} if {@code null}
+ */
+ public static Boolean toBooleanObject(int value) {
+ return value == 0 ? Boolean.FALSE : Boolean.TRUE;
+ }
+
+ /**
+ * Converts an Integer to a Boolean using the convention that {@code zero}
+ * is {@code false}.
+ *
+ * {@code null} will be converted to {@code null}.
+ *
+ * NOTE: This returns null and will throw a NullPointerException if autoboxed to a boolean.
+ *
+ *
+ * BooleanUtils.toBoolean(Integer.valueOf(0)) = Boolean.FALSE
+ * BooleanUtils.toBoolean(Integer.valueOf(1)) = Boolean.TRUE
+ * BooleanUtils.toBoolean(Integer.valueOf(null)) = null
+ *
+ *
+ * @param value the Integer to convert
+ * @return Boolean.TRUE if non-zero, Boolean.FALSE if zero,
+ * {@code null} if {@code null} input
+ */
+ public static Boolean toBooleanObject(Integer value) {
+ if (value == null) {
+ return null;
+ }
+ return value.intValue() == 0 ? Boolean.FALSE : Boolean.TRUE;
+ }
+
+ /**
+ * Converts an int to a boolean specifying the conversion values.
+ *
+ *
+ * BooleanUtils.toBoolean(0, 1, 0) = false
+ * BooleanUtils.toBoolean(1, 1, 0) = true
+ * BooleanUtils.toBoolean(2, 1, 2) = false
+ * BooleanUtils.toBoolean(2, 2, 0) = true
+ *
+ *
+ * @param value the Integer to convert
+ * @param trueValue the value to match for {@code true}
+ * @param falseValue the value to match for {@code false}
+ * @return {@code true} or {@code false}
+ * @throws IllegalArgumentException if no match
+ */
+ public static boolean toBoolean(int value, int trueValue, int falseValue) {
+ if (value == trueValue) {
+ return true;
+ }
+ if (value == falseValue) {
+ return false;
+ }
+ // no match
+ throw new IllegalArgumentException("The Integer did not match either specified value");
+ }
+
+ /**
+ * Converts an Integer to a boolean specifying the conversion values.
+ *
+ *
+ * BooleanUtils.toBoolean(Integer.valueOf(0), Integer.valueOf(1), Integer.valueOf(0)) = false
+ * BooleanUtils.toBoolean(Integer.valueOf(1), Integer.valueOf(1), Integer.valueOf(0)) = true
+ * BooleanUtils.toBoolean(Integer.valueOf(2), Integer.valueOf(1), Integer.valueOf(2)) = false
+ * BooleanUtils.toBoolean(Integer.valueOf(2), Integer.valueOf(2), Integer.valueOf(0)) = true
+ * BooleanUtils.toBoolean(null, null, Integer.valueOf(0)) = true
+ *
+ *
+ * @param value the Integer to convert
+ * @param trueValue the value to match for {@code true}, may be {@code null}
+ * @param falseValue the value to match for {@code false}, may be {@code null}
+ * @return {@code true} or {@code false}
+ * @throws IllegalArgumentException if no match
+ */
+ public static boolean toBoolean(Integer value, Integer trueValue, Integer falseValue) {
+ if (value == null) {
+ if (trueValue == null) {
+ return true;
+ }
+ if (falseValue == null) {
+ return false;
+ }
+ } else if (value.equals(trueValue)) {
+ return true;
+ } else if (value.equals(falseValue)) {
+ return false;
+ }
+ // no match
+ throw new IllegalArgumentException("The Integer did not match either specified value");
+ }
+
+ /**
+ * Converts an int to a Boolean specifying the conversion values.
+ *
+ * NOTE: This returns null and will throw a NullPointerException if autoboxed to a boolean.
+ *
+ *
+ * BooleanUtils.toBooleanObject(0, 0, 2, 3) = Boolean.TRUE
+ * BooleanUtils.toBooleanObject(2, 1, 2, 3) = Boolean.FALSE
+ * BooleanUtils.toBooleanObject(3, 1, 2, 3) = null
+ *
+ *
+ * @param value the Integer to convert
+ * @param trueValue the value to match for {@code true}
+ * @param falseValue the value to match for {@code false}
+ * @param nullValue the value to to match for {@code null}
+ * @return Boolean.TRUE, Boolean.FALSE, or {@code null}
+ * @throws IllegalArgumentException if no match
+ */
+ public static Boolean toBooleanObject(int value, int trueValue, int falseValue, int nullValue) {
+ if (value == trueValue) {
+ return Boolean.TRUE;
+ }
+ if (value == falseValue) {
+ return Boolean.FALSE;
+ }
+ if (value == nullValue) {
+ return null;
+ }
+ // no match
+ throw new IllegalArgumentException("The Integer did not match any specified value");
+ }
+
+ /**
+ * Converts an Integer to a Boolean specifying the conversion values.
+ *
+ * NOTE: This returns null and will throw a NullPointerException if autoboxed to a boolean.
+ *
+ *
+ * BooleanUtils.toBooleanObject(Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(2), Integer.valueOf(3)) = Boolean.TRUE
+ * BooleanUtils.toBooleanObject(Integer.valueOf(2), Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3)) = Boolean.FALSE
+ * BooleanUtils.toBooleanObject(Integer.valueOf(3), Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3)) = null
+ *
+ *
+ * @param value the Integer to convert
+ * @param trueValue the value to match for {@code true}, may be {@code null}
+ * @param falseValue the value to match for {@code false}, may be {@code null}
+ * @param nullValue the value to to match for {@code null}, may be {@code null}
+ * @return Boolean.TRUE, Boolean.FALSE, or {@code null}
+ * @throws IllegalArgumentException if no match
+ */
+ public static Boolean toBooleanObject(Integer value, Integer trueValue, Integer falseValue, Integer nullValue) {
+ if (value == null) {
+ if (trueValue == null) {
+ return Boolean.TRUE;
+ }
+ if (falseValue == null) {
+ return Boolean.FALSE;
+ }
+ if (nullValue == null) {
+ return null;
+ }
+ } else if (value.equals(trueValue)) {
+ return Boolean.TRUE;
+ } else if (value.equals(falseValue)) {
+ return Boolean.FALSE;
+ } else if (value.equals(nullValue)) {
+ return null;
+ }
+ // no match
+ throw new IllegalArgumentException("The Integer did not match any specified value");
+ }
+
+ // Boolean to Integer methods
+ //-----------------------------------------------------------------------
+ /**
+ * Converts a boolean to an int using the convention that
+ * {@code zero} is {@code false}.
+ *
+ *
+ * BooleanUtils.toInteger(true) = 1
+ * BooleanUtils.toInteger(false) = 0
+ *
+ *
+ * @param bool the boolean to convert
+ * @return one if {@code true}, zero if {@code false}
+ */
+ public static int toInteger(boolean bool) {
+ return bool ? 1 : 0;
+ }
+
+ /**
+ * Converts a boolean to an Integer using the convention that
+ * {@code zero} is {@code false}.
+ *
+ *
+ * BooleanUtils.toIntegerObject(true) = Integer.valueOf(1)
+ * BooleanUtils.toIntegerObject(false) = Integer.valueOf(0)
+ *
+ *
+ * @param bool the boolean to convert
+ * @return one if {@code true}, zero if {@code false}
+ */
+ public static Integer toIntegerObject(boolean bool) {
+ return bool ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO;
+ }
+
+ /**
+ * Converts a Boolean to a Integer using the convention that
+ * {@code zero} is {@code false}.
+ *
+ * {@code null} will be converted to {@code null}.
+ *
+ *
+ * BooleanUtils.toIntegerObject(Boolean.TRUE) = Integer.valueOf(1)
+ * BooleanUtils.toIntegerObject(Boolean.FALSE) = Integer.valueOf(0)
+ *
+ *
+ * @param bool the Boolean to convert
+ * @return one if Boolean.TRUE, zero if Boolean.FALSE, {@code null} if {@code null}
+ */
+ public static Integer toIntegerObject(Boolean bool) {
+ if (bool == null) {
+ return null;
+ }
+ return bool.booleanValue() ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO;
+ }
+
+ /**
+ * Converts a boolean to an int specifying the conversion values.
+ *
+ *
+ * BooleanUtils.toInteger(true, 1, 0) = 1
+ * BooleanUtils.toInteger(false, 1, 0) = 0
+ *
+ *
+ * @param bool the to convert
+ * @param trueValue the value to return if {@code true}
+ * @param falseValue the value to return if {@code false}
+ * @return the appropriate value
+ */
+ public static int toInteger(boolean bool, int trueValue, int falseValue) {
+ return bool ? trueValue : falseValue;
+ }
+
+ /**
+ * Converts a Boolean to an int specifying the conversion values.
+ *
+ *
+ * BooleanUtils.toInteger(Boolean.TRUE, 1, 0, 2) = 1
+ * BooleanUtils.toInteger(Boolean.FALSE, 1, 0, 2) = 0
+ * BooleanUtils.toInteger(null, 1, 0, 2) = 2
+ *
+ *
+ * @param bool the Boolean to convert
+ * @param trueValue the value to return if {@code true}
+ * @param falseValue the value to return if {@code false}
+ * @param nullValue the value to return if {@code null}
+ * @return the appropriate value
+ */
+ public static int toInteger(Boolean bool, int trueValue, int falseValue, int nullValue) {
+ if (bool == null) {
+ return nullValue;
+ }
+ return bool.booleanValue() ? trueValue : falseValue;
+ }
+
+ /**
+ * Converts a boolean to an Integer specifying the conversion values.
+ *
+ *
+ * BooleanUtils.toIntegerObject(true, Integer.valueOf(1), Integer.valueOf(0)) = Integer.valueOf(1)
+ * BooleanUtils.toIntegerObject(false, Integer.valueOf(1), Integer.valueOf(0)) = Integer.valueOf(0)
+ *
+ *
+ * @param bool the to convert
+ * @param trueValue the value to return if {@code true}, may be {@code null}
+ * @param falseValue the value to return if {@code false}, may be {@code null}
+ * @return the appropriate value
+ */
+ public static Integer toIntegerObject(boolean bool, Integer trueValue, Integer falseValue) {
+ return bool ? trueValue : falseValue;
+ }
+
+ /**
+ * Converts a Boolean to an Integer specifying the conversion values.
+ *
+ *
+ * BooleanUtils.toIntegerObject(Boolean.TRUE, Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(2)) = Integer.valueOf(1)
+ * BooleanUtils.toIntegerObject(Boolean.FALSE, Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(2)) = Integer.valueOf(0)
+ * BooleanUtils.toIntegerObject(null, Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(2)) = Integer.valueOf(2)
+ *
+ *
+ * @param bool the Boolean to convert
+ * @param trueValue the value to return if {@code true}, may be {@code null}
+ * @param falseValue the value to return if {@code false}, may be {@code null}
+ * @param nullValue the value to return if {@code null}, may be {@code null}
+ * @return the appropriate value
+ */
+ public static Integer toIntegerObject(Boolean bool, Integer trueValue, Integer falseValue, Integer nullValue) {
+ if (bool == null) {
+ return nullValue;
+ }
+ return bool.booleanValue() ? trueValue : falseValue;
+ }
+
+ // String to Boolean methods
+ //-----------------------------------------------------------------------
+ /**
+ * Converts a String to a Boolean.
+ *
+ * {@code 'true'}, {@code 'on'} or {@code 'yes'}
+ * (case insensitive) will return {@code true}.
+ * {@code 'false'}, {@code 'off'} or {@code 'no'}
+ * (case insensitive) will return {@code false}.
+ * Otherwise, {@code null} is returned.
+ *
+ * NOTE: This returns null and will throw a NullPointerException if autoboxed to a boolean.
+ *
+ *
+ * BooleanUtils.toBooleanObject(null) = null
+ * BooleanUtils.toBooleanObject("true") = Boolean.TRUE
+ * BooleanUtils.toBooleanObject("false") = Boolean.FALSE
+ * BooleanUtils.toBooleanObject("on") = Boolean.TRUE
+ * BooleanUtils.toBooleanObject("ON") = Boolean.TRUE
+ * BooleanUtils.toBooleanObject("off") = Boolean.FALSE
+ * BooleanUtils.toBooleanObject("oFf") = Boolean.FALSE
+ * BooleanUtils.toBooleanObject("blue") = null
+ *
+ *
+ * @param str the String to check
+ * @return the Boolean value of the string, {@code null} if no match or {@code null} input
+ */
+ public static Boolean toBooleanObject(String str) {
+ // Previously used equalsIgnoreCase, which was fast for interned 'true'.
+ // Non interned 'true' matched 15 times slower.
+ //
+ // Optimisation provides same performance as before for interned 'true'.
+ // Similar performance for null, 'false', and other strings not length 2/3/4.
+ // 'true'/'TRUE' match 4 times slower, 'tRUE'/'True' 7 times slower.
+ if (str == "true") {
+ return Boolean.TRUE;
+ }
+ if (str == null) {
+ return null;
+ }
+ switch (str.length()) {
+ case 1: {
+ char ch0 = str.charAt(0);
+ if (ch0 == 'y' || ch0 == 'Y' ||
+ ch0 == 't' || ch0 == 'T') {
+ return Boolean.TRUE;
+ }
+ if (ch0 == 'n' || ch0 == 'N' ||
+ ch0 == 'f' || ch0 == 'F') {
+ return Boolean.FALSE;
+ }
+ break;
+ }
+ case 2: {
+ char ch0 = str.charAt(0);
+ char ch1 = str.charAt(1);
+ if ((ch0 == 'o' || ch0 == 'O') &&
+ (ch1 == 'n' || ch1 == 'N') ) {
+ return Boolean.TRUE;
+ }
+ if ((ch0 == 'n' || ch0 == 'N') &&
+ (ch1 == 'o' || ch1 == 'O') ) {
+ return Boolean.FALSE;
+ }
+ break;
+ }
+ case 3: {
+ char ch0 = str.charAt(0);
+ char ch1 = str.charAt(1);
+ char ch2 = str.charAt(2);
+ if ((ch0 == 'y' || ch0 == 'Y') &&
+ (ch1 == 'e' || ch1 == 'E') &&
+ (ch2 == 's' || ch2 == 'S') ) {
+ return Boolean.TRUE;
+ }
+ if ((ch0 == 'o' || ch0 == 'O') &&
+ (ch1 == 'f' || ch1 == 'F') &&
+ (ch2 == 'f' || ch2 == 'F') ) {
+ return Boolean.FALSE;
+ }
+ break;
+ }
+ case 4: {
+ char ch0 = str.charAt(0);
+ char ch1 = str.charAt(1);
+ char ch2 = str.charAt(2);
+ char ch3 = str.charAt(3);
+ if ((ch0 == 't' || ch0 == 'T') &&
+ (ch1 == 'r' || ch1 == 'R') &&
+ (ch2 == 'u' || ch2 == 'U') &&
+ (ch3 == 'e' || ch3 == 'E') ) {
+ return Boolean.TRUE;
+ }
+ break;
+ }
+ case 5: {
+ char ch0 = str.charAt(0);
+ char ch1 = str.charAt(1);
+ char ch2 = str.charAt(2);
+ char ch3 = str.charAt(3);
+ char ch4 = str.charAt(4);
+ if ((ch0 == 'f' || ch0 == 'F') &&
+ (ch1 == 'a' || ch1 == 'A') &&
+ (ch2 == 'l' || ch2 == 'L') &&
+ (ch3 == 's' || ch3 == 'S') &&
+ (ch4 == 'e' || ch4 == 'E') ) {
+ return Boolean.FALSE;
+ }
+ break;
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Converts a String to a Boolean throwing an exception if no match.
+ *
+ * NOTE: This returns null and will throw a NullPointerException if autoboxed to a boolean.
+ *
+ *
+ * BooleanUtils.toBooleanObject("true", "true", "false", "null") = Boolean.TRUE
+ * BooleanUtils.toBooleanObject("false", "true", "false", "null") = Boolean.FALSE
+ * BooleanUtils.toBooleanObject("null", "true", "false", "null") = null
+ *
+ *
+ * @param str the String to check
+ * @param trueString the String to match for {@code true} (case sensitive), may be {@code null}
+ * @param falseString the String to match for {@code false} (case sensitive), may be {@code null}
+ * @param nullString the String to match for {@code null} (case sensitive), may be {@code null}
+ * @return the Boolean value of the string, {@code null} if either the String matches {@code nullString}
+ * or if {@code null} input and {@code nullString} is {@code null}
+ * @throws IllegalArgumentException if the String doesn't match
+ */
+ public static Boolean toBooleanObject(String str, String trueString, String falseString, String nullString) {
+ if (str == null) {
+ if (trueString == null) {
+ return Boolean.TRUE;
+ }
+ if (falseString == null) {
+ return Boolean.FALSE;
+ }
+ if (nullString == null) {
+ return null;
+ }
+ } else if (str.equals(trueString)) {
+ return Boolean.TRUE;
+ } else if (str.equals(falseString)) {
+ return Boolean.FALSE;
+ } else if (str.equals(nullString)) {
+ return null;
+ }
+ // no match
+ throw new IllegalArgumentException("The String did not match any specified value");
+ }
+
+ // String to boolean methods
+ //-----------------------------------------------------------------------
+ /**
+ * Converts a String to a boolean (optimised for performance).
+ *
+ * {@code 'true'}, {@code 'on'} or {@code 'yes'}
+ * (case insensitive) will return {@code true}. Otherwise,
+ * {@code false} is returned.
+ *
+ * This method performs 4 times faster (JDK1.4) than
+ * {@code Boolean.valueOf(String)}. However, this method accepts
+ * 'on' and 'yes' as true values.
+ *
+ *
+ * BooleanUtils.toBoolean(null) = false
+ * BooleanUtils.toBoolean("true") = true
+ * BooleanUtils.toBoolean("TRUE") = true
+ * BooleanUtils.toBoolean("tRUe") = true
+ * BooleanUtils.toBoolean("on") = true
+ * BooleanUtils.toBoolean("yes") = true
+ * BooleanUtils.toBoolean("false") = false
+ * BooleanUtils.toBoolean("x gti") = false
+ *
+ *
+ * @param str the String to check
+ * @return the boolean value of the string, {@code false} if no match or the String is null
+ */
+ public static boolean toBoolean(String str) {
+ return toBooleanObject(str) == Boolean.TRUE;
+ }
+
+ /**
+ * Converts a String to a Boolean throwing an exception if no match found.
+ *
+ *
+ * BooleanUtils.toBoolean("true", "true", "false") = true
+ * BooleanUtils.toBoolean("false", "true", "false") = false
+ *
+ *
+ * @param str the String to check
+ * @param trueString the String to match for {@code true} (case sensitive), may be {@code null}
+ * @param falseString the String to match for {@code false} (case sensitive), may be {@code null}
+ * @return the boolean value of the string
+ * @throws IllegalArgumentException if the String doesn't match
+ */
+ public static boolean toBoolean(String str, String trueString, String falseString) {
+ if (str == trueString) {
+ return true;
+ } else if (str == falseString) {
+ return false;
+ } else if (str != null) {
+ if (str.equals(trueString)) {
+ return true;
+ } else if (str.equals(falseString)) {
+ return false;
+ }
+ }
+ // no match
+ throw new IllegalArgumentException("The String did not match either specified value");
+ }
+
+ // Boolean to String methods
+ //-----------------------------------------------------------------------
+ /**
+ * Converts a Boolean to a String returning {@code 'true'},
+ * {@code 'false'}, or {@code null}.
+ *
+ *
+ * BooleanUtils.toStringTrueFalse(Boolean.TRUE) = "true"
+ * BooleanUtils.toStringTrueFalse(Boolean.FALSE) = "false"
+ * BooleanUtils.toStringTrueFalse(null) = null;
+ *
+ *
+ * @param bool the Boolean to check
+ * @return {@code 'true'}, {@code 'false'}, or {@code null}
+ */
+ public static String toStringTrueFalse(Boolean bool) {
+ return toString(bool, "true", "false", null);
+ }
+
+ /**
+ * Converts a Boolean to a String returning {@code 'on'},
+ * {@code 'off'}, or {@code null}.
+ *
+ *
+ * BooleanUtils.toStringOnOff(Boolean.TRUE) = "on"
+ * BooleanUtils.toStringOnOff(Boolean.FALSE) = "off"
+ * BooleanUtils.toStringOnOff(null) = null;
+ *
+ *
+ * @param bool the Boolean to check
+ * @return {@code 'on'}, {@code 'off'}, or {@code null}
+ */
+ public static String toStringOnOff(Boolean bool) {
+ return toString(bool, "on", "off", null);
+ }
+
+ /**
+ * Converts a Boolean to a String returning {@code 'yes'},
+ * {@code 'no'}, or {@code null}.
+ *
+ *
+ * BooleanUtils.toStringYesNo(Boolean.TRUE) = "yes"
+ * BooleanUtils.toStringYesNo(Boolean.FALSE) = "no"
+ * BooleanUtils.toStringYesNo(null) = null;
+ *
+ *
+ * @param bool the Boolean to check
+ * @return {@code 'yes'}, {@code 'no'}, or {@code null}
+ */
+ public static String toStringYesNo(Boolean bool) {
+ return toString(bool, "yes", "no", null);
+ }
+
+ /**
+ * Converts a Boolean to a String returning one of the input Strings.
+ *
+ *
+ * BooleanUtils.toString(Boolean.TRUE, "true", "false", null) = "true"
+ * BooleanUtils.toString(Boolean.FALSE, "true", "false", null) = "false"
+ * BooleanUtils.toString(null, "true", "false", null) = null;
+ *
+ *
+ * @param bool the Boolean to check
+ * @param trueString the String to return if {@code true}, may be {@code null}
+ * @param falseString the String to return if {@code false}, may be {@code null}
+ * @param nullString the String to return if {@code null}, may be {@code null}
+ * @return one of the three input Strings
+ */
+ public static String toString(Boolean bool, String trueString, String falseString, String nullString) {
+ if (bool == null) {
+ return nullString;
+ }
+ return bool.booleanValue() ? trueString : falseString;
+ }
+
+ // boolean to String methods
+ //-----------------------------------------------------------------------
+ /**
+ * Converts a boolean to a String returning {@code 'true'}
+ * or {@code 'false'}.
+ *
+ *
+ * BooleanUtils.toStringTrueFalse(true) = "true"
+ * BooleanUtils.toStringTrueFalse(false) = "false"
+ *
+ *
+ * @param bool the Boolean to check
+ * @return {@code 'true'}, {@code 'false'}, or {@code null}
+ */
+ public static String toStringTrueFalse(boolean bool) {
+ return toString(bool, "true", "false");
+ }
+
+ /**
+ * Converts a boolean to a String returning {@code 'on'}
+ * or {@code 'off'}.
+ *
+ *
+ * BooleanUtils.toStringOnOff(true) = "on"
+ * BooleanUtils.toStringOnOff(false) = "off"
+ *
+ *
+ * @param bool the Boolean to check
+ * @return {@code 'on'}, {@code 'off'}, or {@code null}
+ */
+ public static String toStringOnOff(boolean bool) {
+ return toString(bool, "on", "off");
+ }
+
+ /**
+ * Converts a boolean to a String returning {@code 'yes'}
+ * or {@code 'no'}.
+ *
+ *
+ * BooleanUtils.toStringYesNo(true) = "yes"
+ * BooleanUtils.toStringYesNo(false) = "no"
+ *
+ *
+ * @param bool the Boolean to check
+ * @return {@code 'yes'}, {@code 'no'}, or {@code null}
+ */
+ public static String toStringYesNo(boolean bool) {
+ return toString(bool, "yes", "no");
+ }
+
+ /**
+ * Converts a boolean to a String returning one of the input Strings.
+ *
+ *
+ * BooleanUtils.toString(true, "true", "false") = "true"
+ * BooleanUtils.toString(false, "true", "false") = "false"
+ *
+ *
+ * @param bool the Boolean to check
+ * @param trueString the String to return if {@code true}, may be {@code null}
+ * @param falseString the String to return if {@code false}, may be {@code null}
+ * @return one of the two input Strings
+ */
+ public static String toString(boolean bool, String trueString, String falseString) {
+ return bool ? trueString : falseString;
+ }
+
+ // logical operations
+ // ----------------------------------------------------------------------
+ /**
+ * Performs an and on a set of booleans.
+ *
+ *
+ * BooleanUtils.and(true, true) = true
+ * BooleanUtils.and(false, false) = false
+ * BooleanUtils.and(true, false) = false
+ * BooleanUtils.and(true, true, false) = false
+ * BooleanUtils.and(true, true, true) = true
+ *
+ *
+ * @param array an array of {@code boolean}s
+ * @return {@code true} if the and is successful.
+ * @throws IllegalArgumentException if {@code array} is {@code null}
+ * @throws IllegalArgumentException if {@code array} is empty.
+ * @since 3.0.1
+ */
+ public static boolean and(boolean... array) {
+ // Validates input
+ if (array == null) {
+ throw new IllegalArgumentException("The Array must not be null");
+ }
+ if (array.length == 0) {
+ throw new IllegalArgumentException("Array is empty");
+ }
+ for (boolean element : array) {
+ if (!element) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Performs an and on an array of Booleans.
+ *
+ *
+ * BooleanUtils.and(Boolean.TRUE, Boolean.TRUE) = Boolean.TRUE
+ * BooleanUtils.and(Boolean.FALSE, Boolean.FALSE) = Boolean.FALSE
+ * BooleanUtils.and(Boolean.TRUE, Boolean.FALSE) = Boolean.FALSE
+ * BooleanUtils.and(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE) = Boolean.TRUE
+ * BooleanUtils.and(Boolean.FALSE, Boolean.FALSE, Boolean.TRUE) = Boolean.FALSE
+ * BooleanUtils.and(Boolean.TRUE, Boolean.FALSE, Boolean.TRUE) = Boolean.FALSE
+ *
+ *
+ * @param array an array of {@code Boolean}s
+ * @return {@code true} if the and is successful.
+ * @throws IllegalArgumentException if {@code array} is {@code null}
+ * @throws IllegalArgumentException if {@code array} is empty.
+ * @throws IllegalArgumentException if {@code array} contains a {@code null}
+ * @since 3.0.1
+ */
+ public static Boolean and(Boolean... array) {
+ if (array == null) {
+ throw new IllegalArgumentException("The Array must not be null");
+ }
+ if (array.length == 0) {
+ throw new IllegalArgumentException("Array is empty");
+ }
+ try {
+ boolean[] primitive = ArrayUtils.toPrimitive(array);
+ return and(primitive) ? Boolean.TRUE : Boolean.FALSE;
+ } catch (NullPointerException ex) {
+ throw new IllegalArgumentException("The array must not contain any null elements");
+ }
+ }
+
+ /**
+ * Performs an or on a set of booleans.
+ *
+ *
+ * BooleanUtils.or(true, true) = true
+ * BooleanUtils.or(false, false) = false
+ * BooleanUtils.or(true, false) = true
+ * BooleanUtils.or(true, true, false) = true
+ * BooleanUtils.or(true, true, true) = true
+ * BooleanUtils.or(false, false, false) = false
+ *
+ *
+ * @param array an array of {@code boolean}s
+ * @return {@code true} if the or is successful.
+ * @throws IllegalArgumentException if {@code array} is {@code null}
+ * @throws IllegalArgumentException if {@code array} is empty.
+ * @since 3.0.1
+ */
+ public static boolean or(boolean... array) {
+ // Validates input
+ if (array == null) {
+ throw new IllegalArgumentException("The Array must not be null");
+ }
+ if (array.length == 0) {
+ throw new IllegalArgumentException("Array is empty");
+ }
+ for (boolean element : array) {
+ if (element) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Performs an or on an array of Booleans.
+ *
+ *
+ * BooleanUtils.or(Boolean.TRUE, Boolean.TRUE) = Boolean.TRUE
+ * BooleanUtils.or(Boolean.FALSE, Boolean.FALSE) = Boolean.FALSE
+ * BooleanUtils.or(Boolean.TRUE, Boolean.FALSE) = Boolean.TRUE
+ * BooleanUtils.or(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE) = Boolean.TRUE
+ * BooleanUtils.or(Boolean.FALSE, Boolean.FALSE, Boolean.TRUE) = Boolean.TRUE
+ * BooleanUtils.or(Boolean.TRUE, Boolean.FALSE, Boolean.TRUE) = Boolean.TRUE
+ * BooleanUtils.or(Boolean.FALSE, Boolean.FALSE, Boolean.FALSE) = Boolean.FALSE
+ *
+ *
+ * @param array an array of {@code Boolean}s
+ * @return {@code true} if the or is successful.
+ * @throws IllegalArgumentException if {@code array} is {@code null}
+ * @throws IllegalArgumentException if {@code array} is empty.
+ * @throws IllegalArgumentException if {@code array} contains a {@code null}
+ * @since 3.0.1
+ */
+ public static Boolean or(Boolean... array) {
+ if (array == null) {
+ throw new IllegalArgumentException("The Array must not be null");
+ }
+ if (array.length == 0) {
+ throw new IllegalArgumentException("Array is empty");
+ }
+ try {
+ boolean[] primitive = ArrayUtils.toPrimitive(array);
+ return or(primitive) ? Boolean.TRUE : Boolean.FALSE;
+ } catch (NullPointerException ex) {
+ throw new IllegalArgumentException("The array must not contain any null elements");
+ }
+ }
+
+ /**
+ * Performs an xor on a set of booleans.
+ *
+ *
+ * BooleanUtils.xor(true, true) = false
+ * BooleanUtils.xor(false, false) = false
+ * BooleanUtils.xor(true, false) = true
+ * BooleanUtils.xor(true, true) = false
+ * BooleanUtils.xor(false, false) = false
+ * BooleanUtils.xor(true, false) = true
+ *
+ *
+ * @param array an array of {@code boolean}s
+ * @return {@code true} if the xor is successful.
+ * @throws IllegalArgumentException if {@code array} is {@code null}
+ * @throws IllegalArgumentException if {@code array} is empty.
+ */
+ public static boolean xor(boolean... array) {
+ // Validates input
+ if (array == null) {
+ throw new IllegalArgumentException("The Array must not be null");
+ }
+ if (array.length == 0) {
+ throw new IllegalArgumentException("Array is empty");
+ }
+
+ // Loops through array, comparing each item
+ int trueCount = 0;
+ for (boolean element : array) {
+ // If item is true, and trueCount is < 1, increments count
+ // Else, xor fails
+ if (element) {
+ if (trueCount < 1) {
+ trueCount++;
+ } else {
+ return false;
+ }
+ }
+ }
+
+ // Returns true if there was exactly 1 true item
+ return trueCount == 1;
+ }
+
+ /**
+ * Performs an xor on an array of Booleans.
+ *
+ *
+ * BooleanUtils.xor(new Boolean[] { Boolean.TRUE, Boolean.TRUE }) = Boolean.FALSE
+ * BooleanUtils.xor(new Boolean[] { Boolean.FALSE, Boolean.FALSE }) = Boolean.FALSE
+ * BooleanUtils.xor(new Boolean[] { Boolean.TRUE, Boolean.FALSE }) = Boolean.TRUE
+ *
+ *
+ * @param array an array of {@code Boolean}s
+ * @return {@code true} if the xor is successful.
+ * @throws IllegalArgumentException if {@code array} is {@code null}
+ * @throws IllegalArgumentException if {@code array} is empty.
+ * @throws IllegalArgumentException if {@code array} contains a {@code null}
+ */
+ public static Boolean xor(Boolean... array) {
+ if (array == null) {
+ throw new IllegalArgumentException("The Array must not be null");
+ }
+ if (array.length == 0) {
+ throw new IllegalArgumentException("Array is empty");
+ }
+ try {
+ boolean[] primitive = ArrayUtils.toPrimitive(array);
+ return xor(primitive) ? Boolean.TRUE : Boolean.FALSE;
+ } catch (NullPointerException ex) {
+ throw new IllegalArgumentException("The array must not contain any null elements");
+ }
+ }
+
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/BooleanUtilsTest.java b/ApacheCommonsLang/org/apache/commons/lang3/BooleanUtilsTest.java
new file mode 100644
index 0000000..2d4079c
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/BooleanUtilsTest.java
@@ -0,0 +1,984 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+package org.apache.commons.lang3;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Modifier;
+
+import org.junit.Test;
+
+/**
+ * Unit tests {@link org.apache.commons.lang3.BooleanUtils}.
+ *
+ * @version $Id: BooleanUtilsTest.java 1309910 2012-04-05 15:52:43Z ggregory $
+ */
+public class BooleanUtilsTest {
+
+ //-----------------------------------------------------------------------
+ @Test
+ public void testConstructor() {
+ assertNotNull(new BooleanUtils());
+ Constructor>[] cons = BooleanUtils.class.getDeclaredConstructors();
+ assertEquals(1, cons.length);
+ assertTrue(Modifier.isPublic(cons[0].getModifiers()));
+ assertTrue(Modifier.isPublic(BooleanUtils.class.getModifiers()));
+ assertFalse(Modifier.isFinal(BooleanUtils.class.getModifiers()));
+ }
+
+ //-----------------------------------------------------------------------
+ @Test
+ public void test_negate_Boolean() {
+ assertSame(null, BooleanUtils.negate(null));
+ assertSame(Boolean.TRUE, BooleanUtils.negate(Boolean.FALSE));
+ assertSame(Boolean.FALSE, BooleanUtils.negate(Boolean.TRUE));
+ }
+
+ //-----------------------------------------------------------------------
+ @Test
+ public void test_isTrue_Boolean() {
+ assertTrue(BooleanUtils.isTrue(Boolean.TRUE));
+ assertFalse(BooleanUtils.isTrue(Boolean.FALSE));
+ assertFalse(BooleanUtils.isTrue((Boolean) null));
+ }
+
+ @Test
+ public void test_isNotTrue_Boolean() {
+ assertFalse(BooleanUtils.isNotTrue(Boolean.TRUE));
+ assertTrue(BooleanUtils.isNotTrue(Boolean.FALSE));
+ assertTrue(BooleanUtils.isNotTrue((Boolean) null));
+ }
+
+ //-----------------------------------------------------------------------
+ @Test
+ public void test_isFalse_Boolean() {
+ assertFalse(BooleanUtils.isFalse(Boolean.TRUE));
+ assertTrue(BooleanUtils.isFalse(Boolean.FALSE));
+ assertFalse(BooleanUtils.isFalse((Boolean) null));
+ }
+
+ @Test
+ public void test_isNotFalse_Boolean() {
+ assertTrue(BooleanUtils.isNotFalse(Boolean.TRUE));
+ assertFalse(BooleanUtils.isNotFalse(Boolean.FALSE));
+ assertTrue(BooleanUtils.isNotFalse((Boolean) null));
+ }
+
+ //-----------------------------------------------------------------------
+ @Test
+ public void test_toBoolean_Boolean() {
+ assertTrue(BooleanUtils.toBoolean(Boolean.TRUE));
+ assertFalse(BooleanUtils.toBoolean(Boolean.FALSE));
+ assertFalse(BooleanUtils.toBoolean((Boolean) null));
+ }
+
+ @Test
+ public void test_toBooleanDefaultIfNull_Boolean_boolean() {
+ assertTrue(BooleanUtils.toBooleanDefaultIfNull(Boolean.TRUE, true));
+ assertTrue(BooleanUtils.toBooleanDefaultIfNull(Boolean.TRUE, false));
+ assertFalse(BooleanUtils.toBooleanDefaultIfNull(Boolean.FALSE, true));
+ assertFalse(BooleanUtils.toBooleanDefaultIfNull(Boolean.FALSE, false));
+ assertTrue(BooleanUtils.toBooleanDefaultIfNull((Boolean) null, true));
+ assertFalse(BooleanUtils.toBooleanDefaultIfNull((Boolean) null, false));
+ }
+
+ //-----------------------------------------------------------------------
+ //-----------------------------------------------------------------------
+ @Test
+ public void test_toBoolean_int() {
+ assertTrue(BooleanUtils.toBoolean(1));
+ assertTrue(BooleanUtils.toBoolean(-1));
+ assertFalse(BooleanUtils.toBoolean(0));
+ }
+
+ @Test
+ public void test_toBooleanObject_int() {
+ assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(1));
+ assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(-1));
+ assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject(0));
+ }
+
+ @Test
+ public void test_toBooleanObject_Integer() {
+ assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(Integer.valueOf(1)));
+ assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(Integer.valueOf(-1)));
+ assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject(Integer.valueOf(0)));
+ assertEquals(null, BooleanUtils.toBooleanObject((Integer) null));
+ }
+
+ //-----------------------------------------------------------------------
+ @Test
+ public void test_toBoolean_int_int_int() {
+ assertTrue(BooleanUtils.toBoolean(6, 6, 7));
+ assertFalse(BooleanUtils.toBoolean(7, 6, 7));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void test_toBoolean_int_int_int_noMatch() {
+ BooleanUtils.toBoolean(8, 6, 7);
+ }
+
+ @Test
+ public void test_toBoolean_Integer_Integer_Integer() {
+ Integer six = Integer.valueOf(6);
+ Integer seven = Integer.valueOf(7);
+
+ assertTrue(BooleanUtils.toBoolean((Integer) null, null, seven));
+ assertFalse(BooleanUtils.toBoolean((Integer) null, six, null));
+
+ assertTrue(BooleanUtils.toBoolean(Integer.valueOf(6), six, seven));
+ assertFalse(BooleanUtils.toBoolean(Integer.valueOf(7), six, seven));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void test_toBoolean_Integer_Integer_Integer_nullValue() {
+ BooleanUtils.toBoolean(null, Integer.valueOf(6), Integer.valueOf(7));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void test_toBoolean_Integer_Integer_Integer_noMatch() {
+ BooleanUtils.toBoolean(Integer.valueOf(8), Integer.valueOf(6), Integer.valueOf(7));
+ }
+
+ //-----------------------------------------------------------------------
+ @Test
+ public void test_toBooleanObject_int_int_int() {
+ assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(6, 6, 7, 8));
+ assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject(7, 6, 7, 8));
+ assertEquals(null, BooleanUtils.toBooleanObject(8, 6, 7, 8));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void test_toBooleanObject_int_int_int_noMatch() {
+ BooleanUtils.toBooleanObject(9, 6, 7, 8);
+ }
+
+ @Test
+ public void test_toBooleanObject_Integer_Integer_Integer_Integer() {
+ Integer six = Integer.valueOf(6);
+ Integer seven = Integer.valueOf(7);
+ Integer eight = Integer.valueOf(8);
+
+ assertSame(Boolean.TRUE, BooleanUtils.toBooleanObject((Integer) null, null, seven, eight));
+ assertSame(Boolean.FALSE, BooleanUtils.toBooleanObject((Integer) null, six, null, eight));
+ assertSame(null, BooleanUtils.toBooleanObject((Integer) null, six, seven, null));
+
+ assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(Integer.valueOf(6), six, seven, eight));
+ assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject(Integer.valueOf(7), six, seven, eight));
+ assertEquals(null, BooleanUtils.toBooleanObject(Integer.valueOf(8), six, seven, eight));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void test_toBooleanObject_Integer_Integer_Integer_Integer_nullValue() {
+ BooleanUtils.toBooleanObject(null, Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void test_toBooleanObject_Integer_Integer_Integer_Integer_noMatch() {
+ BooleanUtils.toBooleanObject(Integer.valueOf(9), Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8));
+ }
+
+ //-----------------------------------------------------------------------
+ @Test
+ public void test_toInteger_boolean() {
+ assertEquals(1, BooleanUtils.toInteger(true));
+ assertEquals(0, BooleanUtils.toInteger(false));
+ }
+
+ @Test
+ public void test_toIntegerObject_boolean() {
+ assertEquals(Integer.valueOf(1), BooleanUtils.toIntegerObject(true));
+ assertEquals(Integer.valueOf(0), BooleanUtils.toIntegerObject(false));
+ }
+
+ @Test
+ public void test_toIntegerObject_Boolean() {
+ assertEquals(Integer.valueOf(1), BooleanUtils.toIntegerObject(Boolean.TRUE));
+ assertEquals(Integer.valueOf(0), BooleanUtils.toIntegerObject(Boolean.FALSE));
+ assertEquals(null, BooleanUtils.toIntegerObject((Boolean) null));
+ }
+
+ //-----------------------------------------------------------------------
+ @Test
+ public void test_toInteger_boolean_int_int() {
+ assertEquals(6, BooleanUtils.toInteger(true, 6, 7));
+ assertEquals(7, BooleanUtils.toInteger(false, 6, 7));
+ }
+
+ @Test
+ public void test_toInteger_Boolean_int_int_int() {
+ assertEquals(6, BooleanUtils.toInteger(Boolean.TRUE, 6, 7, 8));
+ assertEquals(7, BooleanUtils.toInteger(Boolean.FALSE, 6, 7, 8));
+ assertEquals(8, BooleanUtils.toInteger(null, 6, 7, 8));
+ }
+
+ @Test
+ public void test_toIntegerObject_boolean_Integer_Integer() {
+ Integer six = Integer.valueOf(6);
+ Integer seven = Integer.valueOf(7);
+ assertEquals(six, BooleanUtils.toIntegerObject(true, six, seven));
+ assertEquals(seven, BooleanUtils.toIntegerObject(false, six, seven));
+ }
+
+ @Test
+ public void test_toIntegerObject_Boolean_Integer_Integer_Integer() {
+ Integer six = Integer.valueOf(6);
+ Integer seven = Integer.valueOf(7);
+ Integer eight = Integer.valueOf(8);
+ assertEquals(six, BooleanUtils.toIntegerObject(Boolean.TRUE, six, seven, eight));
+ assertEquals(seven, BooleanUtils.toIntegerObject(Boolean.FALSE, six, seven, eight));
+ assertEquals(eight, BooleanUtils.toIntegerObject((Boolean) null, six, seven, eight));
+ assertEquals(null, BooleanUtils.toIntegerObject((Boolean) null, six, seven, null));
+ }
+
+ //-----------------------------------------------------------------------
+ //-----------------------------------------------------------------------
+ @Test
+ public void test_toBooleanObject_String() {
+ assertEquals(null, BooleanUtils.toBooleanObject((String) null));
+ assertEquals(null, BooleanUtils.toBooleanObject(""));
+ assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("false"));
+ assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("no"));
+ assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("off"));
+ assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("FALSE"));
+ assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("NO"));
+ assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("OFF"));
+ assertEquals(null, BooleanUtils.toBooleanObject("oof"));
+ assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("true"));
+ assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("yes"));
+ assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("on"));
+ assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("TRUE"));
+ assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("ON"));
+ assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("YES"));
+ assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("TruE"));
+ assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("TruE"));
+
+ assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("y"));
+ assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("Y"));
+ assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("t"));
+ assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("T"));
+ assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("f"));
+ assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("F"));
+ assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("n"));
+ assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("N"));
+ assertEquals(null, BooleanUtils.toBooleanObject("z"));
+
+ assertEquals(null, BooleanUtils.toBooleanObject("ab"));
+ assertEquals(null, BooleanUtils.toBooleanObject("yoo"));
+ }
+
+ @Test
+ public void test_toBooleanObject_String_String_String_String() {
+ assertSame(Boolean.TRUE, BooleanUtils.toBooleanObject((String) null, null, "N", "U"));
+ assertSame(Boolean.FALSE, BooleanUtils.toBooleanObject((String) null, "Y", null, "U"));
+ assertSame(null, BooleanUtils.toBooleanObject((String) null, "Y", "N", null));
+
+ assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("Y", "Y", "N", "U"));
+ assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("N", "Y", "N", "U"));
+ assertEquals(null, BooleanUtils.toBooleanObject("U", "Y", "N", "U"));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void test_toBooleanObject_String_String_String_String_nullValue() {
+ BooleanUtils.toBooleanObject((String) null, "Y", "N", "U");
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void test_toBooleanObject_String_String_String_String_noMatch() {
+ BooleanUtils.toBooleanObject("X", "Y", "N", "U");
+ }
+
+ //-----------------------------------------------------------------------
+ @Test
+ public void test_toBoolean_String() {
+ assertFalse(BooleanUtils.toBoolean((String) null));
+ assertFalse(BooleanUtils.toBoolean(""));
+ assertFalse(BooleanUtils.toBoolean("off"));
+ assertFalse(BooleanUtils.toBoolean("oof"));
+ assertFalse(BooleanUtils.toBoolean("yep"));
+ assertFalse(BooleanUtils.toBoolean("trux"));
+ assertFalse(BooleanUtils.toBoolean("false"));
+ assertFalse(BooleanUtils.toBoolean("a"));
+ assertTrue(BooleanUtils.toBoolean("true")); // interned handled differently
+ assertTrue(BooleanUtils.toBoolean(new StringBuffer("tr").append("ue").toString()));
+ assertTrue(BooleanUtils.toBoolean("truE"));
+ assertTrue(BooleanUtils.toBoolean("trUe"));
+ assertTrue(BooleanUtils.toBoolean("trUE"));
+ assertTrue(BooleanUtils.toBoolean("tRue"));
+ assertTrue(BooleanUtils.toBoolean("tRuE"));
+ assertTrue(BooleanUtils.toBoolean("tRUe"));
+ assertTrue(BooleanUtils.toBoolean("tRUE"));
+ assertTrue(BooleanUtils.toBoolean("TRUE"));
+ assertTrue(BooleanUtils.toBoolean("TRUe"));
+ assertTrue(BooleanUtils.toBoolean("TRuE"));
+ assertTrue(BooleanUtils.toBoolean("TRue"));
+ assertTrue(BooleanUtils.toBoolean("TrUE"));
+ assertTrue(BooleanUtils.toBoolean("TrUe"));
+ assertTrue(BooleanUtils.toBoolean("TruE"));
+ assertTrue(BooleanUtils.toBoolean("True"));
+ assertTrue(BooleanUtils.toBoolean("on"));
+ assertTrue(BooleanUtils.toBoolean("oN"));
+ assertTrue(BooleanUtils.toBoolean("On"));
+ assertTrue(BooleanUtils.toBoolean("ON"));
+ assertTrue(BooleanUtils.toBoolean("yes"));
+ assertTrue(BooleanUtils.toBoolean("yeS"));
+ assertTrue(BooleanUtils.toBoolean("yEs"));
+ assertTrue(BooleanUtils.toBoolean("yES"));
+ assertTrue(BooleanUtils.toBoolean("Yes"));
+ assertTrue(BooleanUtils.toBoolean("YeS"));
+ assertTrue(BooleanUtils.toBoolean("YEs"));
+ assertTrue(BooleanUtils.toBoolean("YES"));
+ assertFalse(BooleanUtils.toBoolean("yes?"));
+ assertFalse(BooleanUtils.toBoolean("tru"));
+
+ assertFalse(BooleanUtils.toBoolean("no"));
+ assertFalse(BooleanUtils.toBoolean("off"));
+ assertFalse(BooleanUtils.toBoolean("yoo"));
+ }
+
+ @Test
+ public void test_toBoolean_String_String_String() {
+ assertTrue(BooleanUtils.toBoolean((String) null, null, "N"));
+ assertFalse(BooleanUtils.toBoolean((String) null, "Y", null));
+ assertTrue(BooleanUtils.toBoolean("Y", "Y", "N"));
+ assertTrue(BooleanUtils.toBoolean("Y", new String("Y"), new String("N")));
+ assertFalse(BooleanUtils.toBoolean("N", "Y", "N"));
+ assertFalse(BooleanUtils.toBoolean("N", new String("Y"), new String("N")));
+ assertTrue(BooleanUtils.toBoolean((String) null, null, null));
+ assertTrue(BooleanUtils.toBoolean("Y", "Y", "Y"));
+ assertTrue(BooleanUtils.toBoolean("Y", new String("Y"), new String("Y")));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void test_toBoolean_String_String_String_nullValue() {
+ BooleanUtils.toBoolean(null, "Y", "N");
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void test_toBoolean_String_String_String_noMatch() {
+ BooleanUtils.toBoolean("X", "Y", "N");
+ }
+
+ //-----------------------------------------------------------------------
+ @Test
+ public void test_toStringTrueFalse_Boolean() {
+ assertEquals(null, BooleanUtils.toStringTrueFalse((Boolean) null));
+ assertEquals("true", BooleanUtils.toStringTrueFalse(Boolean.TRUE));
+ assertEquals("false", BooleanUtils.toStringTrueFalse(Boolean.FALSE));
+ }
+
+ @Test
+ public void test_toStringOnOff_Boolean() {
+ assertEquals(null, BooleanUtils.toStringOnOff((Boolean) null));
+ assertEquals("on", BooleanUtils.toStringOnOff(Boolean.TRUE));
+ assertEquals("off", BooleanUtils.toStringOnOff(Boolean.FALSE));
+ }
+
+ @Test
+ public void test_toStringYesNo_Boolean() {
+ assertEquals(null, BooleanUtils.toStringYesNo((Boolean) null));
+ assertEquals("yes", BooleanUtils.toStringYesNo(Boolean.TRUE));
+ assertEquals("no", BooleanUtils.toStringYesNo(Boolean.FALSE));
+ }
+
+ @Test
+ public void test_toString_Boolean_String_String_String() {
+ assertEquals("U", BooleanUtils.toString((Boolean) null, "Y", "N", "U"));
+ assertEquals("Y", BooleanUtils.toString(Boolean.TRUE, "Y", "N", "U"));
+ assertEquals("N", BooleanUtils.toString(Boolean.FALSE, "Y", "N", "U"));
+ }
+
+ //-----------------------------------------------------------------------
+ @Test
+ public void test_toStringTrueFalse_boolean() {
+ assertEquals("true", BooleanUtils.toStringTrueFalse(true));
+ assertEquals("false", BooleanUtils.toStringTrueFalse(false));
+ }
+
+ @Test
+ public void test_toStringOnOff_boolean() {
+ assertEquals("on", BooleanUtils.toStringOnOff(true));
+ assertEquals("off", BooleanUtils.toStringOnOff(false));
+ }
+
+ @Test
+ public void test_toStringYesNo_boolean() {
+ assertEquals("yes", BooleanUtils.toStringYesNo(true));
+ assertEquals("no", BooleanUtils.toStringYesNo(false));
+ }
+
+ @Test
+ public void test_toString_boolean_String_String_String() {
+ assertEquals("Y", BooleanUtils.toString(true, "Y", "N"));
+ assertEquals("N", BooleanUtils.toString(false, "Y", "N"));
+ }
+
+ // testXor
+ // -----------------------------------------------------------------------
+ @Test(expected = IllegalArgumentException.class)
+ public void testXor_primitive_nullInput() {
+ BooleanUtils.xor((boolean[]) null);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testXor_primitive_emptyInput() {
+ BooleanUtils.xor(new boolean[] {});
+ }
+
+ @Test
+ public void testXor_primitive_validInput_2items() {
+ assertTrue(
+ "True result for (true, true)",
+ ! BooleanUtils.xor(new boolean[] { true, true }));
+
+ assertTrue(
+ "True result for (false, false)",
+ ! BooleanUtils.xor(new boolean[] { false, false }));
+
+ assertTrue(
+ "False result for (true, false)",
+ BooleanUtils.xor(new boolean[] { true, false }));
+
+ assertTrue(
+ "False result for (false, true)",
+ BooleanUtils.xor(new boolean[] { false, true }));
+ }
+
+ @Test
+ public void testXor_primitive_validInput_3items() {
+ assertTrue(
+ "False result for (false, false, true)",
+ BooleanUtils.xor(new boolean[] { false, false, true }));
+
+ assertTrue(
+ "False result for (false, true, false)",
+ BooleanUtils.xor(new boolean[] { false, true, false }));
+
+ assertTrue(
+ "False result for (true, false, false)",
+ BooleanUtils.xor(new boolean[] { true, false, false }));
+
+ assertTrue(
+ "True result for (true, true, true)",
+ ! BooleanUtils.xor(new boolean[] { true, true, true }));
+
+ assertTrue(
+ "True result for (false, false)",
+ ! BooleanUtils.xor(new boolean[] { false, false, false }));
+
+ assertTrue(
+ "True result for (true, true, false)",
+ ! BooleanUtils.xor(new boolean[] { true, true, false }));
+
+ assertTrue(
+ "True result for (true, false, true)",
+ ! BooleanUtils.xor(new boolean[] { true, false, true }));
+
+ assertTrue(
+ "False result for (false, true, true)",
+ ! BooleanUtils.xor(new boolean[] { false, true, true }));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testXor_object_nullInput() {
+ BooleanUtils.xor((Boolean[]) null);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testXor_object_emptyInput() {
+ BooleanUtils.xor(new Boolean[] {});
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testXor_object_nullElementInput() {
+ BooleanUtils.xor(new Boolean[] {null});
+ }
+
+ @Test
+ public void testXor_object_validInput_2items() {
+ assertTrue(
+ "True result for (true, true)",
+ ! BooleanUtils
+ .xor(new Boolean[] { Boolean.TRUE, Boolean.TRUE })
+ .booleanValue());
+
+ assertTrue(
+ "True result for (false, false)",
+ ! BooleanUtils
+ .xor(new Boolean[] { Boolean.FALSE, Boolean.FALSE })
+ .booleanValue());
+
+ assertTrue(
+ "False result for (true, false)",
+ BooleanUtils
+ .xor(new Boolean[] { Boolean.TRUE, Boolean.FALSE })
+ .booleanValue());
+
+ assertTrue(
+ "False result for (false, true)",
+ BooleanUtils
+ .xor(new Boolean[] { Boolean.FALSE, Boolean.TRUE })
+ .booleanValue());
+ }
+
+ @Test
+ public void testXor_object_validInput_3items() {
+ assertTrue(
+ "False result for (false, false, true)",
+ BooleanUtils
+ .xor(
+ new Boolean[] {
+ Boolean.FALSE,
+ Boolean.FALSE,
+ Boolean.TRUE })
+ .booleanValue());
+
+ assertTrue(
+ "False result for (false, true, false)",
+ BooleanUtils
+ .xor(
+ new Boolean[] {
+ Boolean.FALSE,
+ Boolean.TRUE,
+ Boolean.FALSE })
+ .booleanValue());
+
+ assertTrue(
+ "False result for (true, false, false)",
+ BooleanUtils
+ .xor(
+ new Boolean[] {
+ Boolean.TRUE,
+ Boolean.FALSE,
+ Boolean.FALSE })
+ .booleanValue());
+
+ assertTrue(
+ "True result for (true, true, true)",
+ ! BooleanUtils
+ .xor(new Boolean[] { Boolean.TRUE, Boolean.TRUE, Boolean.TRUE })
+ .booleanValue());
+
+ assertTrue(
+ "True result for (false, false)",
+ ! BooleanUtils.xor(
+ new Boolean[] {
+ Boolean.FALSE,
+ Boolean.FALSE,
+ Boolean.FALSE })
+ .booleanValue());
+
+ assertTrue(
+ "True result for (true, true, false)",
+ ! BooleanUtils.xor(
+ new Boolean[] {
+ Boolean.TRUE,
+ Boolean.TRUE,
+ Boolean.FALSE })
+ .booleanValue());
+
+ assertTrue(
+ "True result for (true, false, true)",
+ ! BooleanUtils.xor(
+ new Boolean[] {
+ Boolean.TRUE,
+ Boolean.FALSE,
+ Boolean.TRUE })
+ .booleanValue());
+
+ assertTrue(
+ "False result for (false, true, true)",
+ ! BooleanUtils.xor(
+ new Boolean[] {
+ Boolean.FALSE,
+ Boolean.TRUE,
+ Boolean.TRUE })
+ .booleanValue());
+ }
+
+ // testAnd
+ // -----------------------------------------------------------------------
+ @Test(expected = IllegalArgumentException.class)
+ public void testAnd_primitive_nullInput() {
+ BooleanUtils.and((boolean[]) null);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testAnd_primitive_emptyInput() {
+ BooleanUtils.and(new boolean[] {});
+ }
+
+ @Test
+ public void testAnd_primitive_validInput_2items() {
+ assertTrue(
+ "False result for (true, true)",
+ BooleanUtils.and(new boolean[] { true, true }));
+
+ assertTrue(
+ "True result for (false, false)",
+ ! BooleanUtils.and(new boolean[] { false, false }));
+
+ assertTrue(
+ "True result for (true, false)",
+ ! BooleanUtils.and(new boolean[] { true, false }));
+
+ assertTrue(
+ "True result for (false, true)",
+ ! BooleanUtils.and(new boolean[] { false, true }));
+ }
+
+ @Test
+ public void testAnd_primitive_validInput_3items() {
+ assertTrue(
+ "True result for (false, false, true)",
+ ! BooleanUtils.and(new boolean[] { false, false, true }));
+
+ assertTrue(
+ "True result for (false, true, false)",
+ ! BooleanUtils.and(new boolean[] { false, true, false }));
+
+ assertTrue(
+ "True result for (true, false, false)",
+ ! BooleanUtils.and(new boolean[] { true, false, false }));
+
+ assertTrue(
+ "False result for (true, true, true)",
+ BooleanUtils.and(new boolean[] { true, true, true }));
+
+ assertTrue(
+ "True result for (false, false)",
+ ! BooleanUtils.and(new boolean[] { false, false, false }));
+
+ assertTrue(
+ "True result for (true, true, false)",
+ ! BooleanUtils.and(new boolean[] { true, true, false }));
+
+ assertTrue(
+ "True result for (true, false, true)",
+ ! BooleanUtils.and(new boolean[] { true, false, true }));
+
+ assertTrue(
+ "True result for (false, true, true)",
+ ! BooleanUtils.and(new boolean[] { false, true, true }));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testAnd_object_nullInput() {
+ BooleanUtils.and((Boolean[]) null);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testAnd_object_emptyInput() {
+ BooleanUtils.and(new Boolean[] {});
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testAnd_object_nullElementInput() {
+ BooleanUtils.and(new Boolean[] {null});
+ }
+
+ @Test
+ public void testAnd_object_validInput_2items() {
+ assertTrue(
+ "False result for (true, true)",
+ BooleanUtils
+ .and(new Boolean[] { Boolean.TRUE, Boolean.TRUE })
+ .booleanValue());
+
+ assertTrue(
+ "True result for (false, false)",
+ ! BooleanUtils
+ .and(new Boolean[] { Boolean.FALSE, Boolean.FALSE })
+ .booleanValue());
+
+ assertTrue(
+ "True result for (true, false)",
+ ! BooleanUtils
+ .and(new Boolean[] { Boolean.TRUE, Boolean.FALSE })
+ .booleanValue());
+
+ assertTrue(
+ "True result for (false, true)",
+ ! BooleanUtils
+ .and(new Boolean[] { Boolean.FALSE, Boolean.TRUE })
+ .booleanValue());
+ }
+
+ @Test
+ public void testAnd_object_validInput_3items() {
+ assertTrue(
+ "True result for (false, false, true)",
+ ! BooleanUtils
+ .and(
+ new Boolean[] {
+ Boolean.FALSE,
+ Boolean.FALSE,
+ Boolean.TRUE })
+ .booleanValue());
+
+ assertTrue(
+ "True result for (false, true, false)",
+ ! BooleanUtils
+ .and(
+ new Boolean[] {
+ Boolean.FALSE,
+ Boolean.TRUE,
+ Boolean.FALSE })
+ .booleanValue());
+
+ assertTrue(
+ "True result for (true, false, false)",
+ ! BooleanUtils
+ .and(
+ new Boolean[] {
+ Boolean.TRUE,
+ Boolean.FALSE,
+ Boolean.FALSE })
+ .booleanValue());
+
+ assertTrue(
+ "False result for (true, true, true)",
+ BooleanUtils
+ .and(new Boolean[] { Boolean.TRUE, Boolean.TRUE, Boolean.TRUE })
+ .booleanValue());
+
+ assertTrue(
+ "True result for (false, false)",
+ ! BooleanUtils.and(
+ new Boolean[] {
+ Boolean.FALSE,
+ Boolean.FALSE,
+ Boolean.FALSE })
+ .booleanValue());
+
+ assertTrue(
+ "True result for (true, true, false)",
+ ! BooleanUtils.and(
+ new Boolean[] {
+ Boolean.TRUE,
+ Boolean.TRUE,
+ Boolean.FALSE })
+ .booleanValue());
+
+ assertTrue(
+ "True result for (true, false, true)",
+ ! BooleanUtils.and(
+ new Boolean[] {
+ Boolean.TRUE,
+ Boolean.FALSE,
+ Boolean.TRUE })
+ .booleanValue());
+
+ assertTrue(
+ "True result for (false, true, true)",
+ ! BooleanUtils.and(
+ new Boolean[] {
+ Boolean.FALSE,
+ Boolean.TRUE,
+ Boolean.TRUE })
+ .booleanValue());
+ }
+
+ // testOr
+ // -----------------------------------------------------------------------
+ @Test(expected = IllegalArgumentException.class)
+ public void testOr_primitive_nullInput() {
+ BooleanUtils.or((boolean[]) null);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testOr_primitive_emptyInput() {
+ BooleanUtils.or(new boolean[] {});
+ }
+
+ @Test
+ public void testOr_primitive_validInput_2items() {
+ assertTrue(
+ "False result for (true, true)",
+ BooleanUtils.or(new boolean[] { true, true }));
+
+ assertTrue(
+ "True result for (false, false)",
+ ! BooleanUtils.or(new boolean[] { false, false }));
+
+ assertTrue(
+ "False result for (true, false)",
+ BooleanUtils.or(new boolean[] { true, false }));
+
+ assertTrue(
+ "False result for (false, true)",
+ BooleanUtils.or(new boolean[] { false, true }));
+ }
+
+ @Test
+ public void testOr_primitive_validInput_3items() {
+ assertTrue(
+ "False result for (false, false, true)",
+ BooleanUtils.or(new boolean[] { false, false, true }));
+
+ assertTrue(
+ "False result for (false, true, false)",
+ BooleanUtils.or(new boolean[] { false, true, false }));
+
+ assertTrue(
+ "False result for (true, false, false)",
+ BooleanUtils.or(new boolean[] { true, false, false }));
+
+ assertTrue(
+ "False result for (true, true, true)",
+ BooleanUtils.or(new boolean[] { true, true, true }));
+
+ assertTrue(
+ "True result for (false, false)",
+ ! BooleanUtils.or(new boolean[] { false, false, false }));
+
+ assertTrue(
+ "False result for (true, true, false)",
+ BooleanUtils.or(new boolean[] { true, true, false }));
+
+ assertTrue(
+ "False result for (true, false, true)",
+ BooleanUtils.or(new boolean[] { true, false, true }));
+
+ assertTrue(
+ "False result for (false, true, true)",
+ BooleanUtils.or(new boolean[] { false, true, true }));
+
+ }
+ @Test(expected = IllegalArgumentException.class)
+ public void testOr_object_nullInput() {
+ BooleanUtils.or((Boolean[]) null);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testOr_object_emptyInput() {
+ BooleanUtils.or(new Boolean[] {});
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testOr_object_nullElementInput() {
+ BooleanUtils.or(new Boolean[] {null});
+ }
+
+ @Test
+ public void testOr_object_validInput_2items() {
+ assertTrue(
+ "False result for (true, true)",
+ BooleanUtils
+ .or(new Boolean[] { Boolean.TRUE, Boolean.TRUE })
+ .booleanValue());
+
+ assertTrue(
+ "True result for (false, false)",
+ ! BooleanUtils
+ .or(new Boolean[] { Boolean.FALSE, Boolean.FALSE })
+ .booleanValue());
+
+ assertTrue(
+ "False result for (true, false)",
+ BooleanUtils
+ .or(new Boolean[] { Boolean.TRUE, Boolean.FALSE })
+ .booleanValue());
+
+ assertTrue(
+ "False result for (false, true)",
+ BooleanUtils
+ .or(new Boolean[] { Boolean.FALSE, Boolean.TRUE })
+ .booleanValue());
+ }
+
+ @Test
+ public void testOr_object_validInput_3items() {
+ assertTrue(
+ "False result for (false, false, true)",
+ BooleanUtils
+ .or(
+ new Boolean[] {
+ Boolean.FALSE,
+ Boolean.FALSE,
+ Boolean.TRUE })
+ .booleanValue());
+
+ assertTrue(
+ "False result for (false, true, false)",
+ BooleanUtils
+ .or(
+ new Boolean[] {
+ Boolean.FALSE,
+ Boolean.TRUE,
+ Boolean.FALSE })
+ .booleanValue());
+
+ assertTrue(
+ "False result for (true, false, false)",
+ BooleanUtils
+ .or(
+ new Boolean[] {
+ Boolean.TRUE,
+ Boolean.FALSE,
+ Boolean.FALSE })
+ .booleanValue());
+
+ assertTrue(
+ "False result for (true, true, true)",
+ BooleanUtils
+ .or(new Boolean[] { Boolean.TRUE, Boolean.TRUE, Boolean.TRUE })
+ .booleanValue());
+
+ assertTrue(
+ "True result for (false, false)",
+ ! BooleanUtils.or(
+ new Boolean[] {
+ Boolean.FALSE,
+ Boolean.FALSE,
+ Boolean.FALSE })
+ .booleanValue());
+
+ assertTrue(
+ "False result for (true, true, false)",
+ BooleanUtils.or(
+ new Boolean[] {
+ Boolean.TRUE,
+ Boolean.TRUE,
+ Boolean.FALSE })
+ .booleanValue());
+
+ assertTrue(
+ "False result for (true, false, true)",
+ BooleanUtils.or(
+ new Boolean[] {
+ Boolean.TRUE,
+ Boolean.FALSE,
+ Boolean.TRUE })
+ .booleanValue());
+
+ assertTrue(
+ "False result for (false, true, true)",
+ BooleanUtils.or(
+ new Boolean[] {
+ Boolean.FALSE,
+ Boolean.TRUE,
+ Boolean.TRUE })
+ .booleanValue());
+ }
+
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/CharEncoding.java b/ApacheCommonsLang/org/apache/commons/lang3/CharEncoding.java
new file mode 100644
index 0000000..4b896e1
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/CharEncoding.java
@@ -0,0 +1,105 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+package org.apache.commons.lang3;
+
+import java.nio.charset.Charset;
+import java.nio.charset.IllegalCharsetNameException;
+
+/**
+ * Character encoding names required of every implementation of the Java platform.
+ *
+ * According to JRE character
+ * encoding names :
+ *
+ * Every implementation of the Java platform is required to support the following character encodings.
+ * Consult the release documentation for your implementation to see if any other encodings are supported.
+ *
+ *
+ * @see JRE character encoding names
+ * @since 2.1
+ * @version $Id: CharEncoding.java 1088899 2011-04-05 05:31:27Z bayard $
+ */
+public class CharEncoding {
+
+ /**
+ * ISO Latin Alphabet #1, also known as ISO-LATIN-1.
+ *
+ * Every implementation of the Java platform is required to support this character encoding.
+ */
+ public static final String ISO_8859_1 = "ISO-8859-1";
+
+ /**
+ * Seven-bit ASCII, also known as ISO646-US, also known as the Basic Latin block
+ * of the Unicode character set.
+ *
+ * Every implementation of the Java platform is required to support this character encoding.
+ */
+ public static final String US_ASCII = "US-ASCII";
+
+ /**
+ * Sixteen-bit Unicode Transformation Format, byte order specified by a mandatory initial
+ * byte-order mark (either order accepted on input, big-endian used on output).
+ *
+ * Every implementation of the Java platform is required to support this character encoding.
+ */
+ public static final String UTF_16 = "UTF-16";
+
+ /**
+ * Sixteen-bit Unicode Transformation Format, big-endian byte order.
+ *
+ * Every implementation of the Java platform is required to support this character encoding.
+ */
+ public static final String UTF_16BE = "UTF-16BE";
+
+ /**
+ * Sixteen-bit Unicode Transformation Format, little-endian byte order.
+ *
+ * Every implementation of the Java platform is required to support this character encoding.
+ */
+ public static final String UTF_16LE = "UTF-16LE";
+
+ /**
+ * Eight-bit Unicode Transformation Format.
+ *
+ * Every implementation of the Java platform is required to support this character encoding.
+ */
+ public static final String UTF_8 = "UTF-8";
+
+ //-----------------------------------------------------------------------
+ /**
+ * Returns whether the named charset is supported.
+ *
+ * This is similar to
+ * java.nio.charset.Charset.isSupported(String) but handles more formats
+ *
+ * @param name the name of the requested charset; may be either a canonical name or an alias, null returns false
+ * @return {@code true} if the charset is available in the current Java virtual machine
+ */
+ public static boolean isSupported(String name) {
+ if (name == null) {
+ return false;
+ }
+ try {
+ return Charset.isSupported(name);
+ } catch (IllegalCharsetNameException ex) {
+ return false;
+ }
+ }
+
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/CharEncodingTest.java b/ApacheCommonsLang/org/apache/commons/lang3/CharEncodingTest.java
new file mode 100644
index 0000000..722cade
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/CharEncodingTest.java
@@ -0,0 +1,103 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+package org.apache.commons.lang3;
+
+import static org.apache.commons.lang3.JavaVersion.JAVA_1_1;
+import static org.apache.commons.lang3.JavaVersion.JAVA_1_2;
+import static org.apache.commons.lang3.JavaVersion.JAVA_1_3;
+import junit.framework.TestCase;
+
+/**
+ * Tests CharEncoding.
+ *
+ * @see CharEncoding
+ * @version $Id: CharEncodingTest.java 1088899 2011-04-05 05:31:27Z bayard $
+ */
+public class CharEncodingTest extends TestCase {
+
+ private void assertSupportedEncoding(String name) {
+ assertTrue("Encoding should be supported: " + name, CharEncoding.isSupported(name));
+ }
+
+ /**
+ * The class can be instantiated.
+ */
+ public void testConstructor() {
+ new CharEncoding();
+ }
+
+ public void testMustBeSupportedJava1_3_1() {
+ if (SystemUtils.isJavaVersionAtLeast(JAVA_1_3)) {
+ this.assertSupportedEncoding(CharEncoding.ISO_8859_1);
+ this.assertSupportedEncoding(CharEncoding.US_ASCII);
+ this.assertSupportedEncoding(CharEncoding.UTF_16);
+ this.assertSupportedEncoding(CharEncoding.UTF_16BE);
+ this.assertSupportedEncoding(CharEncoding.UTF_16LE);
+ this.assertSupportedEncoding(CharEncoding.UTF_8);
+ } else {
+ this.warn("Java 1.3 tests not run since the current version is " + SystemUtils.JAVA_SPECIFICATION_VERSION);
+ }
+ }
+
+ public void testSupported() {
+ assertTrue(CharEncoding.isSupported("UTF8"));
+ assertTrue(CharEncoding.isSupported("UTF-8"));
+ assertTrue(CharEncoding.isSupported("ASCII"));
+ }
+
+ public void testNotSupported() {
+ assertFalse(CharEncoding.isSupported(null));
+ assertFalse(CharEncoding.isSupported(""));
+ assertFalse(CharEncoding.isSupported(" "));
+ assertFalse(CharEncoding.isSupported("\t\r\n"));
+ assertFalse(CharEncoding.isSupported("DOESNOTEXIST"));
+ assertFalse(CharEncoding.isSupported("this is not a valid encoding name"));
+ }
+
+ public void testWorksOnJava1_1_8() {
+ //
+ // In this test, I simply deleted the encodings from the 1.3.1 list.
+ // The Javadoc do not specify which encodings are required.
+ //
+ if (SystemUtils.isJavaVersionAtLeast(JAVA_1_1)) {
+ this.assertSupportedEncoding(CharEncoding.ISO_8859_1);
+ this.assertSupportedEncoding(CharEncoding.US_ASCII);
+ this.assertSupportedEncoding(CharEncoding.UTF_8);
+ } else {
+ this.warn("Java 1.1 tests not run since the current version is " + SystemUtils.JAVA_SPECIFICATION_VERSION);
+ }
+ }
+
+ public void testWorksOnJava1_2_2() {
+ //
+ // In this test, I simply deleted the encodings from the 1.3.1 list.
+ // The Javadoc do not specify which encodings are required.
+ //
+ if (SystemUtils.isJavaVersionAtLeast(JAVA_1_2)) {
+ this.assertSupportedEncoding(CharEncoding.ISO_8859_1);
+ this.assertSupportedEncoding(CharEncoding.US_ASCII);
+ this.assertSupportedEncoding(CharEncoding.UTF_8);
+ } else {
+ this.warn("Java 1.2 tests not run since the current version is " + SystemUtils.JAVA_SPECIFICATION_VERSION);
+ }
+ }
+
+ void warn(String msg) {
+ System.err.println(msg);
+ }
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/CharRange.java b/ApacheCommonsLang/org/apache/commons/lang3/CharRange.java
new file mode 100644
index 0000000..cc0495e
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/CharRange.java
@@ -0,0 +1,360 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+package org.apache.commons.lang3;
+
+import java.io.Serializable;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+
+/**
+ * A contiguous range of characters, optionally negated.
+ *
+ * Instances are immutable.
+ *
+ * #ThreadSafe#
+ * @since 1.0
+ * @version $Id: CharRange.java 1309977 2012-04-05 17:53:39Z ggregory $
+ */
+// TODO: This is no longer public and will be removed later as CharSet is moved
+// to depend on Range.
+final class CharRange implements Iterable, Serializable {
+
+ /**
+ * Required for serialization support. Lang version 2.0.
+ *
+ * @see java.io.Serializable
+ */
+ private static final long serialVersionUID = 8270183163158333422L;
+
+ /** The first character, inclusive, in the range. */
+ private final char start;
+ /** The last character, inclusive, in the range. */
+ private final char end;
+ /** True if the range is everything except the characters specified. */
+ private final boolean negated;
+
+ /** Cached toString. */
+ private transient String iToString;
+
+ /**
+ * Constructs a {@code CharRange} over a set of characters,
+ * optionally negating the range.
+ *
+ * A negated range includes everything except that defined by the
+ * start and end characters.
+ *
+ * If start and end are in the wrong order, they are reversed.
+ * Thus {@code a-e} is the same as {@code e-a}.
+ *
+ * @param start first character, inclusive, in this range
+ * @param end last character, inclusive, in this range
+ * @param negated true to express everything except the range
+ */
+ private CharRange(char start, char end, boolean negated) {
+ super();
+ if (start > end) {
+ char temp = start;
+ start = end;
+ end = temp;
+ }
+
+ this.start = start;
+ this.end = end;
+ this.negated = negated;
+ }
+
+ /**
+ * Constructs a {@code CharRange} over a single character.
+ *
+ * @param ch only character in this range
+ * @return the new CharRange object
+ * @see CharRange#CharRange(char, char, boolean)
+ * @since 2.5
+ */
+ public static CharRange is(char ch) {
+ return new CharRange(ch, ch, false);
+ }
+
+ /**
+ * Constructs a negated {@code CharRange} over a single character.
+ *
+ * @param ch only character in this range
+ * @return the new CharRange object
+ * @see CharRange#CharRange(char, char, boolean)
+ * @since 2.5
+ */
+ public static CharRange isNot(char ch) {
+ return new CharRange(ch, ch, true);
+ }
+
+ /**
+ * Constructs a {@code CharRange} over a set of characters.
+ *
+ * @param start first character, inclusive, in this range
+ * @param end last character, inclusive, in this range
+ * @return the new CharRange object
+ * @see CharRange#CharRange(char, char, boolean)
+ * @since 2.5
+ */
+ public static CharRange isIn(char start, char end) {
+ return new CharRange(start, end, false);
+ }
+
+ /**
+ * Constructs a negated {@code CharRange} over a set of characters.
+ *
+ * @param start first character, inclusive, in this range
+ * @param end last character, inclusive, in this range
+ * @return the new CharRange object
+ * @see CharRange#CharRange(char, char, boolean)
+ * @since 2.5
+ */
+ public static CharRange isNotIn(char start, char end) {
+ return new CharRange(start, end, true);
+ }
+
+ // Accessors
+ //-----------------------------------------------------------------------
+ /**
+ * Gets the start character for this character range.
+ *
+ * @return the start char (inclusive)
+ */
+ public char getStart() {
+ return this.start;
+ }
+
+ /**
+ * Gets the end character for this character range.
+ *
+ * @return the end char (inclusive)
+ */
+ public char getEnd() {
+ return this.end;
+ }
+
+ /**
+ * Is this {@code CharRange} negated.
+ *
+ * A negated range includes everything except that defined by the
+ * start and end characters.
+ *
+ * @return {@code true} if negated
+ */
+ public boolean isNegated() {
+ return negated;
+ }
+
+ // Contains
+ //-----------------------------------------------------------------------
+ /**
+ * Is the character specified contained in this range.
+ *
+ * @param ch the character to check
+ * @return {@code true} if this range contains the input character
+ */
+ public boolean contains(char ch) {
+ return (ch >= start && ch <= end) != negated;
+ }
+
+ /**
+ * Are all the characters of the passed in range contained in
+ * this range.
+ *
+ * @param range the range to check against
+ * @return {@code true} if this range entirely contains the input range
+ * @throws IllegalArgumentException if {@code null} input
+ */
+ public boolean contains(CharRange range) {
+ if (range == null) {
+ throw new IllegalArgumentException("The Range must not be null");
+ }
+ if (negated) {
+ if (range.negated) {
+ return start >= range.start && end <= range.end;
+ }
+ return range.end < start || range.start > end;
+ }
+ if (range.negated) {
+ return start == 0 && end == Character.MAX_VALUE;
+ }
+ return start <= range.start && end >= range.end;
+ }
+
+ // Basics
+ //-----------------------------------------------------------------------
+ /**
+ * Compares two CharRange objects, returning true if they represent
+ * exactly the same range of characters defined in the same way.
+ *
+ * @param obj the object to compare to
+ * @return true if equal
+ */
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == this) {
+ return true;
+ }
+ if (obj instanceof CharRange == false) {
+ return false;
+ }
+ CharRange other = (CharRange) obj;
+ return start == other.start && end == other.end && negated == other.negated;
+ }
+
+ /**
+ * Gets a hashCode compatible with the equals method.
+ *
+ * @return a suitable hashCode
+ */
+ @Override
+ public int hashCode() {
+ return 83 + start + 7 * end + (negated ? 1 : 0);
+ }
+
+ /**
+ * Gets a string representation of the character range.
+ *
+ * @return string representation of this range
+ */
+ @Override
+ public String toString() {
+ if (iToString == null) {
+ StringBuilder buf = new StringBuilder(4);
+ if (isNegated()) {
+ buf.append('^');
+ }
+ buf.append(start);
+ if (start != end) {
+ buf.append('-');
+ buf.append(end);
+ }
+ iToString = buf.toString();
+ }
+ return iToString;
+ }
+
+ // Expansions
+ //-----------------------------------------------------------------------
+ /**
+ * Returns an iterator which can be used to walk through the characters described by this range.
+ *
+ * #NotThreadSafe# the iterator is not thread-safe
+ * @return an iterator to the chars represented by this range
+ * @since 2.5
+ */
+ @Override
+ public Iterator iterator() {
+ return new CharacterIterator(this);
+ }
+
+ /**
+ * Character {@link Iterator}.
+ * #NotThreadSafe#
+ */
+ private static class CharacterIterator implements Iterator {
+ /** The current character */
+ private char current;
+
+ private final CharRange range;
+ private boolean hasNext;
+
+ /**
+ * Construct a new iterator for the character range.
+ *
+ * @param r The character range
+ */
+ private CharacterIterator(CharRange r) {
+ range = r;
+ hasNext = true;
+
+ if (range.negated) {
+ if (range.start == 0) {
+ if (range.end == Character.MAX_VALUE) {
+ // This range is an empty set
+ hasNext = false;
+ } else {
+ current = (char) (range.end + 1);
+ }
+ } else {
+ current = 0;
+ }
+ } else {
+ current = range.start;
+ }
+ }
+
+ /**
+ * Prepare the next character in the range.
+ */
+ private void prepareNext() {
+ if (range.negated) {
+ if (current == Character.MAX_VALUE) {
+ hasNext = false;
+ } else if (current + 1 == range.start) {
+ if (range.end == Character.MAX_VALUE) {
+ hasNext = false;
+ } else {
+ current = (char) (range.end + 1);
+ }
+ } else {
+ current = (char) (current + 1);
+ }
+ } else if (current < range.end) {
+ current = (char) (current + 1);
+ } else {
+ hasNext = false;
+ }
+ }
+
+ /**
+ * Has the iterator not reached the end character yet?
+ *
+ * @return {@code true} if the iterator has yet to reach the character date
+ */
+ @Override
+ public boolean hasNext() {
+ return hasNext;
+ }
+
+ /**
+ * Return the next character in the iteration
+ *
+ * @return {@code Character} for the next character
+ */
+ @Override
+ public Character next() {
+ if (hasNext == false) {
+ throw new NoSuchElementException();
+ }
+ char cur = current;
+ prepareNext();
+ return Character.valueOf(cur);
+ }
+
+ /**
+ * Always throws UnsupportedOperationException.
+ *
+ * @throws UnsupportedOperationException
+ * @see java.util.Iterator#remove()
+ */
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ }
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/CharRangeTest.java b/ApacheCommonsLang/org/apache/commons/lang3/CharRangeTest.java
new file mode 100644
index 0000000..99fbe8d
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/CharRangeTest.java
@@ -0,0 +1,383 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+package org.apache.commons.lang3;
+
+import java.lang.reflect.Modifier;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+
+import junit.framework.TestCase;
+
+/**
+ * Unit tests {@link org.apache.commons.lang3.CharRange}.
+ *
+ * @version $Id: CharRangeTest.java 1090427 2011-04-08 20:17:10Z bayard $
+ */
+public class CharRangeTest extends TestCase {
+
+ public CharRangeTest(String name) {
+ super(name);
+ }
+
+ //-----------------------------------------------------------------------
+ public void testClass() {
+ // class changed to non-public in 3.0
+ assertEquals(false, Modifier.isPublic(CharRange.class.getModifiers()));
+ assertEquals(true, Modifier.isFinal(CharRange.class.getModifiers()));
+ }
+
+ //-----------------------------------------------------------------------
+ public void testConstructorAccessors_is() {
+ CharRange rangea = CharRange.is('a');
+ assertEquals('a', rangea.getStart());
+ assertEquals('a', rangea.getEnd());
+ assertEquals(false, rangea.isNegated());
+ assertEquals("a", rangea.toString());
+ }
+
+ public void testConstructorAccessors_isNot() {
+ CharRange rangea = CharRange.isNot('a');
+ assertEquals('a', rangea.getStart());
+ assertEquals('a', rangea.getEnd());
+ assertEquals(true, rangea.isNegated());
+ assertEquals("^a", rangea.toString());
+ }
+
+ public void testConstructorAccessors_isIn_Same() {
+ CharRange rangea = CharRange.isIn('a', 'a');
+ assertEquals('a', rangea.getStart());
+ assertEquals('a', rangea.getEnd());
+ assertEquals(false, rangea.isNegated());
+ assertEquals("a", rangea.toString());
+ }
+
+ public void testConstructorAccessors_isIn_Normal() {
+ CharRange rangea = CharRange.isIn('a', 'e');
+ assertEquals('a', rangea.getStart());
+ assertEquals('e', rangea.getEnd());
+ assertEquals(false, rangea.isNegated());
+ assertEquals("a-e", rangea.toString());
+ }
+
+ public void testConstructorAccessors_isIn_Reversed() {
+ CharRange rangea = CharRange.isIn('e', 'a');
+ assertEquals('a', rangea.getStart());
+ assertEquals('e', rangea.getEnd());
+ assertEquals(false, rangea.isNegated());
+ assertEquals("a-e", rangea.toString());
+ }
+
+ public void testConstructorAccessors_isNotIn_Same() {
+ CharRange rangea = CharRange.isNotIn('a', 'a');
+ assertEquals('a', rangea.getStart());
+ assertEquals('a', rangea.getEnd());
+ assertEquals(true, rangea.isNegated());
+ assertEquals("^a", rangea.toString());
+ }
+
+ public void testConstructorAccessors_isNotIn_Normal() {
+ CharRange rangea = CharRange.isNotIn('a', 'e');
+ assertEquals('a', rangea.getStart());
+ assertEquals('e', rangea.getEnd());
+ assertEquals(true, rangea.isNegated());
+ assertEquals("^a-e", rangea.toString());
+ }
+
+ public void testConstructorAccessors_isNotIn_Reversed() {
+ CharRange rangea = CharRange.isNotIn('e', 'a');
+ assertEquals('a', rangea.getStart());
+ assertEquals('e', rangea.getEnd());
+ assertEquals(true, rangea.isNegated());
+ assertEquals("^a-e", rangea.toString());
+ }
+
+ //-----------------------------------------------------------------------
+ public void testEquals_Object() {
+ CharRange rangea = CharRange.is('a');
+ CharRange rangeae = CharRange.isIn('a', 'e');
+ CharRange rangenotbf = CharRange.isIn('b', 'f');
+
+ assertEquals(false, rangea.equals(null));
+
+ assertEquals(true, rangea.equals(rangea));
+ assertEquals(true, rangea.equals(CharRange.is('a')));
+ assertEquals(true, rangeae.equals(rangeae));
+ assertEquals(true, rangeae.equals(CharRange.isIn('a', 'e')));
+ assertEquals(true, rangenotbf.equals(rangenotbf));
+ assertEquals(true, rangenotbf.equals(CharRange.isIn('b', 'f')));
+
+ assertEquals(false, rangea.equals(rangeae));
+ assertEquals(false, rangea.equals(rangenotbf));
+ assertEquals(false, rangeae.equals(rangea));
+ assertEquals(false, rangeae.equals(rangenotbf));
+ assertEquals(false, rangenotbf.equals(rangea));
+ assertEquals(false, rangenotbf.equals(rangeae));
+ }
+
+ public void testHashCode() {
+ CharRange rangea = CharRange.is('a');
+ CharRange rangeae = CharRange.isIn('a', 'e');
+ CharRange rangenotbf = CharRange.isIn('b', 'f');
+
+ assertEquals(true, rangea.hashCode() == rangea.hashCode());
+ assertEquals(true, rangea.hashCode() == CharRange.is('a').hashCode());
+ assertEquals(true, rangeae.hashCode() == rangeae.hashCode());
+ assertEquals(true, rangeae.hashCode() == CharRange.isIn('a', 'e').hashCode());
+ assertEquals(true, rangenotbf.hashCode() == rangenotbf.hashCode());
+ assertEquals(true, rangenotbf.hashCode() == CharRange.isIn('b', 'f').hashCode());
+
+ assertEquals(false, rangea.hashCode() == rangeae.hashCode());
+ assertEquals(false, rangea.hashCode() == rangenotbf.hashCode());
+ assertEquals(false, rangeae.hashCode() == rangea.hashCode());
+ assertEquals(false, rangeae.hashCode() == rangenotbf.hashCode());
+ assertEquals(false, rangenotbf.hashCode() == rangea.hashCode());
+ assertEquals(false, rangenotbf.hashCode() == rangeae.hashCode());
+ }
+
+ //-----------------------------------------------------------------------
+ public void testContains_Char() {
+ CharRange range = CharRange.is('c');
+ assertEquals(false, range.contains('b'));
+ assertEquals(true, range.contains('c'));
+ assertEquals(false, range.contains('d'));
+ assertEquals(false, range.contains('e'));
+
+ range = CharRange.isIn('c', 'd');
+ assertEquals(false, range.contains('b'));
+ assertEquals(true, range.contains('c'));
+ assertEquals(true, range.contains('d'));
+ assertEquals(false, range.contains('e'));
+
+ range = CharRange.isIn('d', 'c');
+ assertEquals(false, range.contains('b'));
+ assertEquals(true, range.contains('c'));
+ assertEquals(true, range.contains('d'));
+ assertEquals(false, range.contains('e'));
+
+ range = CharRange.isNotIn('c', 'd');
+ assertEquals(true, range.contains('b'));
+ assertEquals(false, range.contains('c'));
+ assertEquals(false, range.contains('d'));
+ assertEquals(true, range.contains('e'));
+ assertEquals(true, range.contains((char) 0));
+ assertEquals(true, range.contains(Character.MAX_VALUE));
+ }
+
+ //-----------------------------------------------------------------------
+ public void testContains_Charrange() {
+ CharRange a = CharRange.is('a');
+ CharRange b = CharRange.is('b');
+ CharRange c = CharRange.is('c');
+ CharRange c2 = CharRange.is('c');
+ CharRange d = CharRange.is('d');
+ CharRange e = CharRange.is('e');
+ CharRange cd = CharRange.isIn('c', 'd');
+ CharRange bd = CharRange.isIn('b', 'd');
+ CharRange bc = CharRange.isIn('b', 'c');
+ CharRange ab = CharRange.isIn('a', 'b');
+ CharRange de = CharRange.isIn('d', 'e');
+ CharRange ef = CharRange.isIn('e', 'f');
+ CharRange ae = CharRange.isIn('a', 'e');
+
+ // normal/normal
+ assertEquals(false, c.contains(b));
+ assertEquals(true, c.contains(c));
+ assertEquals(true, c.contains(c2));
+ assertEquals(false, c.contains(d));
+
+ assertEquals(false, c.contains(cd));
+ assertEquals(false, c.contains(bd));
+ assertEquals(false, c.contains(bc));
+ assertEquals(false, c.contains(ab));
+ assertEquals(false, c.contains(de));
+
+ assertEquals(true, cd.contains(c));
+ assertEquals(true, bd.contains(c));
+ assertEquals(true, bc.contains(c));
+ assertEquals(false, ab.contains(c));
+ assertEquals(false, de.contains(c));
+
+ assertEquals(true, ae.contains(b));
+ assertEquals(true, ae.contains(ab));
+ assertEquals(true, ae.contains(bc));
+ assertEquals(true, ae.contains(cd));
+ assertEquals(true, ae.contains(de));
+
+ CharRange notb = CharRange.isNot('b');
+ CharRange notc = CharRange.isNot('c');
+ CharRange notd = CharRange.isNot('d');
+ CharRange notab = CharRange.isNotIn('a', 'b');
+ CharRange notbc = CharRange.isNotIn('b', 'c');
+ CharRange notbd = CharRange.isNotIn('b', 'd');
+ CharRange notcd = CharRange.isNotIn('c', 'd');
+ CharRange notde = CharRange.isNotIn('d', 'e');
+ CharRange notae = CharRange.isNotIn('a', 'e');
+ CharRange all = CharRange.isIn((char) 0, Character.MAX_VALUE);
+ CharRange allbutfirst = CharRange.isIn((char) 1, Character.MAX_VALUE);
+
+ // normal/negated
+ assertEquals(false, c.contains(notc));
+ assertEquals(false, c.contains(notbd));
+ assertEquals(true, all.contains(notc));
+ assertEquals(true, all.contains(notbd));
+ assertEquals(false, allbutfirst.contains(notc));
+ assertEquals(false, allbutfirst.contains(notbd));
+
+ // negated/normal
+ assertEquals(true, notc.contains(a));
+ assertEquals(true, notc.contains(b));
+ assertEquals(false, notc.contains(c));
+ assertEquals(true, notc.contains(d));
+ assertEquals(true, notc.contains(e));
+
+ assertEquals(true, notc.contains(ab));
+ assertEquals(false, notc.contains(bc));
+ assertEquals(false, notc.contains(bd));
+ assertEquals(false, notc.contains(cd));
+ assertEquals(true, notc.contains(de));
+ assertEquals(false, notc.contains(ae));
+ assertEquals(false, notc.contains(all));
+ assertEquals(false, notc.contains(allbutfirst));
+
+ assertEquals(true, notbd.contains(a));
+ assertEquals(false, notbd.contains(b));
+ assertEquals(false, notbd.contains(c));
+ assertEquals(false, notbd.contains(d));
+ assertEquals(true, notbd.contains(e));
+
+ assertEquals(true, notcd.contains(ab));
+ assertEquals(false, notcd.contains(bc));
+ assertEquals(false, notcd.contains(bd));
+ assertEquals(false, notcd.contains(cd));
+ assertEquals(false, notcd.contains(de));
+ assertEquals(false, notcd.contains(ae));
+ assertEquals(true, notcd.contains(ef));
+ assertEquals(false, notcd.contains(all));
+ assertEquals(false, notcd.contains(allbutfirst));
+
+ // negated/negated
+ assertEquals(false, notc.contains(notb));
+ assertEquals(true, notc.contains(notc));
+ assertEquals(false, notc.contains(notd));
+
+ assertEquals(false, notc.contains(notab));
+ assertEquals(true, notc.contains(notbc));
+ assertEquals(true, notc.contains(notbd));
+ assertEquals(true, notc.contains(notcd));
+ assertEquals(false, notc.contains(notde));
+
+ assertEquals(false, notbd.contains(notb));
+ assertEquals(false, notbd.contains(notc));
+ assertEquals(false, notbd.contains(notd));
+
+ assertEquals(false, notbd.contains(notab));
+ assertEquals(false, notbd.contains(notbc));
+ assertEquals(true, notbd.contains(notbd));
+ assertEquals(false, notbd.contains(notcd));
+ assertEquals(false, notbd.contains(notde));
+ assertEquals(true, notbd.contains(notae));
+ }
+
+ public void testContainsNullArg() {
+ CharRange range = CharRange.is('a');
+ try {
+ @SuppressWarnings("unused")
+ boolean contains = range.contains(null);
+ } catch(IllegalArgumentException e) {
+ assertEquals("The Range must not be null", e.getMessage());
+ }
+ }
+
+ public void testIterator() {
+ CharRange a = CharRange.is('a');
+ CharRange ad = CharRange.isIn('a', 'd');
+ CharRange nota = CharRange.isNot('a');
+ CharRange emptySet = CharRange.isNotIn((char) 0, Character.MAX_VALUE);
+ CharRange notFirst = CharRange.isNotIn((char) 1, Character.MAX_VALUE);
+ CharRange notLast = CharRange.isNotIn((char) 0, (char) (Character.MAX_VALUE - 1));
+
+ Iterator aIt = a.iterator();
+ assertNotNull(aIt);
+ assertTrue(aIt.hasNext());
+ assertEquals(Character.valueOf('a'), aIt.next());
+ assertFalse(aIt.hasNext());
+
+ Iterator adIt = ad.iterator();
+ assertNotNull(adIt);
+ assertTrue(adIt.hasNext());
+ assertEquals(Character.valueOf('a'), adIt.next());
+ assertEquals(Character.valueOf('b'), adIt.next());
+ assertEquals(Character.valueOf('c'), adIt.next());
+ assertEquals(Character.valueOf('d'), adIt.next());
+ assertFalse(adIt.hasNext());
+
+ Iterator notaIt = nota.iterator();
+ assertNotNull(notaIt);
+ assertTrue(notaIt.hasNext());
+ while (notaIt.hasNext()) {
+ Character c = notaIt.next();
+ assertFalse('a' == c.charValue());
+ }
+
+ Iterator emptySetIt = emptySet.iterator();
+ assertNotNull(emptySetIt);
+ assertFalse(emptySetIt.hasNext());
+ try {
+ emptySetIt.next();
+ fail("Should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ assertTrue(true);
+ }
+
+ Iterator notFirstIt = notFirst.iterator();
+ assertNotNull(notFirstIt);
+ assertTrue(notFirstIt.hasNext());
+ assertEquals(Character.valueOf((char) 0), notFirstIt.next());
+ assertFalse(notFirstIt.hasNext());
+ try {
+ notFirstIt.next();
+ fail("Should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ assertTrue(true);
+ }
+
+ Iterator notLastIt = notLast.iterator();
+ assertNotNull(notLastIt);
+ assertTrue(notLastIt.hasNext());
+ assertEquals(Character.valueOf(Character.MAX_VALUE), notLastIt.next());
+ assertFalse(notLastIt.hasNext());
+ try {
+ notLastIt.next();
+ fail("Should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ assertTrue(true);
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ public void testSerialization() {
+ CharRange range = CharRange.is('a');
+ assertEquals(range, SerializationUtils.clone(range));
+ range = CharRange.isIn('a', 'e');
+ assertEquals(range, SerializationUtils.clone(range));
+ range = CharRange.isNotIn('a', 'e');
+ assertEquals(range, SerializationUtils.clone(range));
+ }
+
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/CharSequenceUtils.java b/ApacheCommonsLang/org/apache/commons/lang3/CharSequenceUtils.java
new file mode 100644
index 0000000..40e4923
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/CharSequenceUtils.java
@@ -0,0 +1,197 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+package org.apache.commons.lang3;
+
+/**
+ * Operations on {@link java.lang.CharSequence} that are
+ * {@code null} safe.
+ *
+ * @see java.lang.CharSequence
+ * @since 3.0
+ * @version $Id: CharSequenceUtils.java 1199894 2011-11-09 17:53:59Z ggregory $
+ */
+public class CharSequenceUtils {
+
+ /**
+ * {@code CharSequenceUtils} instances should NOT be constructed in
+ * standard programming.
+ *
+ * This constructor is public to permit tools that require a JavaBean
+ * instance to operate.
+ */
+ public CharSequenceUtils() {
+ super();
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Returns a new {@code CharSequence} that is a subsequence of this
+ * sequence starting with the {@code char} value at the specified index.
+ *
+ * This provides the {@code CharSequence} equivalent to {@link String#substring(int)}.
+ * The length (in {@code char}) of the returned sequence is {@code length() - start},
+ * so if {@code start == end} then an empty sequence is returned.
+ *
+ * @param cs the specified subsequence, null returns null
+ * @param start the start index, inclusive, valid
+ * @return a new subsequence, may be null
+ * @throws IndexOutOfBoundsException if {@code start} is negative or if
+ * {@code start} is greater than {@code length()}
+ */
+ public static CharSequence subSequence(CharSequence cs, int start) {
+ return cs == null ? null : cs.subSequence(start, cs.length());
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Finds the first index in the {@code CharSequence} that matches the
+ * specified character.
+ *
+ * @param cs the {@code CharSequence} to be processed, not null
+ * @param searchChar the char to be searched for
+ * @param start the start index, negative starts at the string start
+ * @return the index where the search char was found, -1 if not found
+ */
+ static int indexOf(CharSequence cs, int searchChar, int start) {
+ if (cs instanceof String) {
+ return ((String) cs).indexOf(searchChar, start);
+ } else {
+ int sz = cs.length();
+ if (start < 0) {
+ start = 0;
+ }
+ for (int i = start; i < sz; i++) {
+ if (cs.charAt(i) == searchChar) {
+ return i;
+ }
+ }
+ return -1;
+ }
+ }
+
+ /**
+ * Used by the indexOf(CharSequence methods) as a green implementation of indexOf.
+ *
+ * @param cs the {@code CharSequence} to be processed
+ * @param searchChar the {@code CharSequence} to be searched for
+ * @param start the start index
+ * @return the index where the search sequence was found
+ */
+ static int indexOf(CharSequence cs, CharSequence searchChar, int start) {
+ return cs.toString().indexOf(searchChar.toString(), start);
+// if (cs instanceof String && searchChar instanceof String) {
+// // TODO: Do we assume searchChar is usually relatively small;
+// // If so then calling toString() on it is better than reverting to
+// // the green implementation in the else block
+// return ((String) cs).indexOf((String) searchChar, start);
+// } else {
+// // TODO: Implement rather than convert to String
+// return cs.toString().indexOf(searchChar.toString(), start);
+// }
+ }
+
+ /**
+ * Finds the last index in the {@code CharSequence} that matches the
+ * specified character.
+ *
+ * @param cs the {@code CharSequence} to be processed
+ * @param searchChar the char to be searched for
+ * @param start the start index, negative returns -1, beyond length starts at end
+ * @return the index where the search char was found, -1 if not found
+ */
+ static int lastIndexOf(CharSequence cs, int searchChar, int start) {
+ if (cs instanceof String) {
+ return ((String) cs).lastIndexOf(searchChar, start);
+ } else {
+ int sz = cs.length();
+ if (start < 0) {
+ return -1;
+ }
+ if (start >= sz) {
+ start = sz - 1;
+ }
+ for (int i = start; i >= 0; --i) {
+ if (cs.charAt(i) == searchChar) {
+ return i;
+ }
+ }
+ return -1;
+ }
+ }
+
+ /**
+ * Used by the lastIndexOf(CharSequence methods) as a green implementation of lastIndexOf
+ *
+ * @param cs the {@code CharSequence} to be processed
+ * @param searchChar the {@code CharSequence} to be searched for
+ * @param start the start index
+ * @return the index where the search sequence was found
+ */
+ static int lastIndexOf(CharSequence cs, CharSequence searchChar, int start) {
+ return cs.toString().lastIndexOf(searchChar.toString(), start);
+// if (cs instanceof String && searchChar instanceof String) {
+// // TODO: Do we assume searchChar is usually relatively small;
+// // If so then calling toString() on it is better than reverting to
+// // the green implementation in the else block
+// return ((String) cs).lastIndexOf((String) searchChar, start);
+// } else {
+// // TODO: Implement rather than convert to String
+// return cs.toString().lastIndexOf(searchChar.toString(), start);
+// }
+ }
+
+ /**
+ * Green implementation of toCharArray.
+ *
+ * @param cs the {@code CharSequence} to be processed
+ * @return the resulting char array
+ */
+ static char[] toCharArray(CharSequence cs) {
+ if (cs instanceof String) {
+ return ((String) cs).toCharArray();
+ } else {
+ int sz = cs.length();
+ char[] array = new char[cs.length()];
+ for (int i = 0; i < sz; i++) {
+ array[i] = cs.charAt(i);
+ }
+ return array;
+ }
+ }
+
+ /**
+ * Green implementation of regionMatches.
+ *
+ * @param cs the {@code CharSequence} to be processed
+ * @param ignoreCase whether or not to be case insensitive
+ * @param thisStart the index to start on the {@code cs} CharSequence
+ * @param substring the {@code CharSequence} to be looked for
+ * @param start the index to start on the {@code substring} CharSequence
+ * @param length character length of the region
+ * @return whether the region matched
+ */
+ static boolean regionMatches(CharSequence cs, boolean ignoreCase, int thisStart,
+ CharSequence substring, int start, int length) {
+ if (cs instanceof String && substring instanceof String) {
+ return ((String) cs).regionMatches(ignoreCase, thisStart, (String) substring, start, length);
+ } else {
+ // TODO: Implement rather than convert to String
+ return cs.toString().regionMatches(ignoreCase, thisStart, substring.toString(), start, length);
+ }
+ }
+
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/CharSequenceUtilsTest.java b/ApacheCommonsLang/org/apache/commons/lang3/CharSequenceUtilsTest.java
new file mode 100644
index 0000000..a8812e7
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/CharSequenceUtilsTest.java
@@ -0,0 +1,75 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+package org.apache.commons.lang3;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Modifier;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
+
+/**
+ * Tests CharSequenceUtils
+ *
+ * @version $Id: CharSequenceUtilsTest.java 1066341 2011-02-02 06:21:53Z bayard $
+ */
+public class CharSequenceUtilsTest extends TestCase {
+
+ //-----------------------------------------------------------------------
+ public void testConstructor() {
+ assertNotNull(new CharSequenceUtils());
+ Constructor>[] cons = CharSequenceUtils.class.getDeclaredConstructors();
+ assertEquals(1, cons.length);
+ assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
+ assertEquals(true, Modifier.isPublic(CharSequenceUtils.class.getModifiers()));
+ assertEquals(false, Modifier.isFinal(CharSequenceUtils.class.getModifiers()));
+ }
+
+ //-----------------------------------------------------------------------
+ public void testSubSequence() {
+ //
+ // null input
+ //
+ Assert.assertEquals(null, CharSequenceUtils.subSequence(null, -1));
+ Assert.assertEquals(null, CharSequenceUtils.subSequence(null, 0));
+ Assert.assertEquals(null, CharSequenceUtils.subSequence(null, 1));
+ //
+ // non-null input
+ //
+ Assert.assertEquals(StringUtils.EMPTY, CharSequenceUtils.subSequence(StringUtils.EMPTY, 0));
+ Assert.assertEquals("012", CharSequenceUtils.subSequence("012", 0));
+ Assert.assertEquals("12", CharSequenceUtils.subSequence("012", 1));
+ Assert.assertEquals("2", CharSequenceUtils.subSequence("012", 2));
+ Assert.assertEquals(StringUtils.EMPTY, CharSequenceUtils.subSequence("012", 3));
+ //
+ // Exception expected
+ //
+ try {
+ Assert.assertEquals(null, CharSequenceUtils.subSequence(StringUtils.EMPTY, -1));
+ Assert.fail("Expected " + IndexOutOfBoundsException.class.getName());
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+ try {
+ Assert.assertEquals(null, CharSequenceUtils.subSequence(StringUtils.EMPTY, 1));
+ Assert.fail("Expected " + IndexOutOfBoundsException.class.getName());
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+ }
+
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/CharSet.java b/ApacheCommonsLang/org/apache/commons/lang3/CharSet.java
new file mode 100644
index 0000000..b7c176f
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/CharSet.java
@@ -0,0 +1,278 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+package org.apache.commons.lang3;
+
+import java.io.Serializable;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A set of characters.
+ *
+ * Instances are immutable, but instances of subclasses may not be.
+ *
+ * #ThreadSafe#
+ * @since 1.0
+ * @version $Id: CharSet.java 1199894 2011-11-09 17:53:59Z ggregory $
+ */
+public class CharSet implements Serializable {
+
+ /**
+ * Required for serialization support. Lang version 2.0.
+ *
+ * @see java.io.Serializable
+ */
+ private static final long serialVersionUID = 5947847346149275958L;
+
+ /**
+ * A CharSet defining no characters.
+ * @since 2.0
+ */
+ public static final CharSet EMPTY = new CharSet((String) null);
+
+ /**
+ * A CharSet defining ASCII alphabetic characters "a-zA-Z".
+ * @since 2.0
+ */
+ public static final CharSet ASCII_ALPHA = new CharSet("a-zA-Z");
+
+ /**
+ * A CharSet defining ASCII alphabetic characters "a-z".
+ * @since 2.0
+ */
+ public static final CharSet ASCII_ALPHA_LOWER = new CharSet("a-z");
+
+ /**
+ * A CharSet defining ASCII alphabetic characters "A-Z".
+ * @since 2.0
+ */
+ public static final CharSet ASCII_ALPHA_UPPER = new CharSet("A-Z");
+
+ /**
+ * A CharSet defining ASCII alphabetic characters "0-9".
+ * @since 2.0
+ */
+ public static final CharSet ASCII_NUMERIC = new CharSet("0-9");
+
+ /**
+ * A Map of the common cases used in the factory.
+ * Subclasses can add more common patterns if desired
+ * @since 2.0
+ */
+ protected static final Map COMMON = Collections.synchronizedMap(new HashMap());
+
+ static {
+ COMMON.put(null, EMPTY);
+ COMMON.put("", EMPTY);
+ COMMON.put("a-zA-Z", ASCII_ALPHA);
+ COMMON.put("A-Za-z", ASCII_ALPHA);
+ COMMON.put("a-z", ASCII_ALPHA_LOWER);
+ COMMON.put("A-Z", ASCII_ALPHA_UPPER);
+ COMMON.put("0-9", ASCII_NUMERIC);
+ }
+
+ /** The set of CharRange objects. */
+ private final Set set = Collections.synchronizedSet(new HashSet());
+
+ //-----------------------------------------------------------------------
+ /**
+ * Factory method to create a new CharSet using a special syntax.
+ *
+ *
+ * {@code null} or empty string ("")
+ * - set containing no characters
+ * Single character, such as "a"
+ * - set containing just that character
+ * Multi character, such as "a-e"
+ * - set containing characters from one character to the other
+ * Negated, such as "^a" or "^a-e"
+ * - set containing all characters except those defined
+ * Combinations, such as "abe-g"
+ * - set containing all the characters from the individual sets
+ *
+ *
+ * The matching order is:
+ *
+ * Negated multi character range, such as "^a-e"
+ * Ordinary multi character range, such as "a-e"
+ * Negated single character, such as "^a"
+ * Ordinary single character, such as "a"
+ *
+ * Matching works left to right. Once a match is found the
+ * search starts again from the next character.
+ *
+ * If the same range is defined twice using the same syntax, only
+ * one range will be kept.
+ * Thus, "a-ca-c" creates only one range of "a-c".
+ *
+ * If the start and end of a range are in the wrong order,
+ * they are reversed. Thus "a-e" is the same as "e-a".
+ * As a result, "a-ee-a" would create only one range,
+ * as the "a-e" and "e-a" are the same.
+ *
+ * The set of characters represented is the union of the specified ranges.
+ *
+ * All CharSet objects returned by this method will be immutable.
+ *
+ * @param setStrs Strings to merge into the set, may be null
+ * @return a CharSet instance
+ * @since 2.4
+ */
+ public static CharSet getInstance(String... setStrs) {
+ if (setStrs == null) {
+ return null;
+ }
+ if (setStrs.length == 1) {
+ CharSet common = COMMON.get(setStrs[0]);
+ if (common != null) {
+ return common;
+ }
+ }
+ return new CharSet(setStrs);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Constructs a new CharSet using the set syntax.
+ * Each string is merged in with the set.
+ *
+ * @param set Strings to merge into the initial set
+ * @throws NullPointerException if set is {@code null}
+ */
+ protected CharSet(String... set) {
+ super();
+ int sz = set.length;
+ for (int i = 0; i < sz; i++) {
+ add(set[i]);
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Add a set definition string to the {@code CharSet}.
+ *
+ * @param str set definition string
+ */
+ protected void add(String str) {
+ if (str == null) {
+ return;
+ }
+
+ int len = str.length();
+ int pos = 0;
+ while (pos < len) {
+ int remainder = len - pos;
+ if (remainder >= 4 && str.charAt(pos) == '^' && str.charAt(pos + 2) == '-') {
+ // negated range
+ set.add(CharRange.isNotIn(str.charAt(pos + 1), str.charAt(pos + 3)));
+ pos += 4;
+ } else if (remainder >= 3 && str.charAt(pos + 1) == '-') {
+ // range
+ set.add(CharRange.isIn(str.charAt(pos), str.charAt(pos + 2)));
+ pos += 3;
+ } else if (remainder >= 2 && str.charAt(pos) == '^') {
+ // negated char
+ set.add(CharRange.isNot(str.charAt(pos + 1)));
+ pos += 2;
+ } else {
+ // char
+ set.add(CharRange.is(str.charAt(pos)));
+ pos += 1;
+ }
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Gets the internal set as an array of CharRange objects.
+ *
+ * @return an array of immutable CharRange objects
+ * @since 2.0
+ */
+// NOTE: This is no longer public as CharRange is no longer a public class.
+// It may be replaced when CharSet moves to Range.
+ /*public*/ CharRange[] getCharRanges() {
+ return set.toArray(new CharRange[set.size()]);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Does the {@code CharSet} contain the specified
+ * character {@code ch}.
+ *
+ * @param ch the character to check for
+ * @return {@code true} if the set contains the characters
+ */
+ public boolean contains(char ch) {
+ for (CharRange range : set) {
+ if (range.contains(ch)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // Basics
+ //-----------------------------------------------------------------------
+ /**
+ * Compares two {@code CharSet} objects, returning true if they represent
+ * exactly the same set of characters defined in the same way.
+ *
+ * The two sets {@code abc} and {@code a-c} are not
+ * equal according to this method.
+ *
+ * @param obj the object to compare to
+ * @return true if equal
+ * @since 2.0
+ */
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == this) {
+ return true;
+ }
+ if (obj instanceof CharSet == false) {
+ return false;
+ }
+ CharSet other = (CharSet) obj;
+ return set.equals(other.set);
+ }
+
+ /**
+ * Gets a hash code compatible with the equals method.
+ *
+ * @return a suitable hash code
+ * @since 2.0
+ */
+ @Override
+ public int hashCode() {
+ return 89 + set.hashCode();
+ }
+
+ /**
+ * Gets a string representation of the set.
+ *
+ * @return string representation of the set
+ */
+ @Override
+ public String toString() {
+ return set.toString();
+ }
+
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/CharSetTest.java b/ApacheCommonsLang/org/apache/commons/lang3/CharSetTest.java
new file mode 100644
index 0000000..b2d430d
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/CharSetTest.java
@@ -0,0 +1,454 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+package org.apache.commons.lang3;
+
+import java.lang.reflect.Modifier;
+
+import junit.framework.TestCase;
+
+/**
+ * Unit tests {@link org.apache.commons.lang3.CharSet}.
+ *
+ * @version $Id: CharSetTest.java 1088899 2011-04-05 05:31:27Z bayard $
+ */
+public class CharSetTest extends TestCase {
+
+ public CharSetTest(String name) {
+ super(name);
+ }
+
+ //-----------------------------------------------------------------------
+ public void testClass() {
+ assertEquals(true, Modifier.isPublic(CharSet.class.getModifiers()));
+ assertEquals(false, Modifier.isFinal(CharSet.class.getModifiers()));
+ }
+
+ //-----------------------------------------------------------------------
+ public void testGetInstance() {
+ assertSame(CharSet.EMPTY, CharSet.getInstance( (String) null));
+ assertSame(CharSet.EMPTY, CharSet.getInstance(""));
+ assertSame(CharSet.ASCII_ALPHA, CharSet.getInstance("a-zA-Z"));
+ assertSame(CharSet.ASCII_ALPHA, CharSet.getInstance("A-Za-z"));
+ assertSame(CharSet.ASCII_ALPHA_LOWER, CharSet.getInstance("a-z"));
+ assertSame(CharSet.ASCII_ALPHA_UPPER, CharSet.getInstance("A-Z"));
+ assertSame(CharSet.ASCII_NUMERIC, CharSet.getInstance("0-9"));
+ }
+
+ //-----------------------------------------------------------------------
+ public void testGetInstance_Stringarray() {
+ assertEquals(null, CharSet.getInstance((String[]) null));
+ assertEquals("[]", CharSet.getInstance(new String[0]).toString());
+ assertEquals("[]", CharSet.getInstance(new String[] {null}).toString());
+ assertEquals("[a-e]", CharSet.getInstance(new String[] {"a-e"}).toString());
+ }
+
+ //-----------------------------------------------------------------------
+ public void testConstructor_String_simple() {
+ CharSet set;
+ CharRange[] array;
+
+ set = CharSet.getInstance((String) null);
+ array = set.getCharRanges();
+ assertEquals("[]", set.toString());
+ assertEquals(0, array.length);
+
+ set = CharSet.getInstance("");
+ array = set.getCharRanges();
+ assertEquals("[]", set.toString());
+ assertEquals(0, array.length);
+
+ set = CharSet.getInstance("a");
+ array = set.getCharRanges();
+ assertEquals("[a]", set.toString());
+ assertEquals(1, array.length);
+ assertEquals("a", array[0].toString());
+
+ set = CharSet.getInstance("^a");
+ array = set.getCharRanges();
+ assertEquals("[^a]", set.toString());
+ assertEquals(1, array.length);
+ assertEquals("^a", array[0].toString());
+
+ set = CharSet.getInstance("a-e");
+ array = set.getCharRanges();
+ assertEquals("[a-e]", set.toString());
+ assertEquals(1, array.length);
+ assertEquals("a-e", array[0].toString());
+
+ set = CharSet.getInstance("^a-e");
+ array = set.getCharRanges();
+ assertEquals("[^a-e]", set.toString());
+ assertEquals(1, array.length);
+ assertEquals("^a-e", array[0].toString());
+ }
+
+ public void testConstructor_String_combo() {
+ CharSet set;
+ CharRange[] array;
+
+ set = CharSet.getInstance("abc");
+ array = set.getCharRanges();
+ assertEquals(3, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('a')));
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('b')));
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('c')));
+
+ set = CharSet.getInstance("a-ce-f");
+ array = set.getCharRanges();
+ assertEquals(2, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('a', 'c')));
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('e', 'f')));
+
+ set = CharSet.getInstance("ae-f");
+ array = set.getCharRanges();
+ assertEquals(2, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('a')));
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('e', 'f')));
+
+ set = CharSet.getInstance("e-fa");
+ array = set.getCharRanges();
+ assertEquals(2, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('a')));
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('e', 'f')));
+
+ set = CharSet.getInstance("ae-fm-pz");
+ array = set.getCharRanges();
+ assertEquals(4, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('a')));
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('e', 'f')));
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('m', 'p')));
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('z')));
+ }
+
+ public void testConstructor_String_comboNegated() {
+ CharSet set;
+ CharRange[] array;
+
+ set = CharSet.getInstance("^abc");
+ array = set.getCharRanges();
+ assertEquals(3, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('a')));
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('b')));
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('c')));
+
+ set = CharSet.getInstance("b^ac");
+ array = set.getCharRanges();
+ assertEquals(3, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('b')));
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('a')));
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('c')));
+
+ set = CharSet.getInstance("db^ac");
+ array = set.getCharRanges();
+ assertEquals(4, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('d')));
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('b')));
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('a')));
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('c')));
+
+ set = CharSet.getInstance("^b^a");
+ array = set.getCharRanges();
+ assertEquals(2, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('b')));
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('a')));
+
+ set = CharSet.getInstance("b^a-c^z");
+ array = set.getCharRanges();
+ assertEquals(3, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isNotIn('a', 'c')));
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('z')));
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('b')));
+ }
+
+ public void testConstructor_String_oddDash() {
+ CharSet set;
+ CharRange[] array;
+
+ set = CharSet.getInstance("-");
+ array = set.getCharRanges();
+ assertEquals(1, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('-')));
+
+ set = CharSet.getInstance("--");
+ array = set.getCharRanges();
+ assertEquals(1, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('-')));
+
+ set = CharSet.getInstance("---");
+ array = set.getCharRanges();
+ assertEquals(1, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('-')));
+
+ set = CharSet.getInstance("----");
+ array = set.getCharRanges();
+ assertEquals(1, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('-')));
+
+ set = CharSet.getInstance("-a");
+ array = set.getCharRanges();
+ assertEquals(2, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('-')));
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('a')));
+
+ set = CharSet.getInstance("a-");
+ array = set.getCharRanges();
+ assertEquals(2, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('a')));
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('-')));
+
+ set = CharSet.getInstance("a--");
+ array = set.getCharRanges();
+ assertEquals(1, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('a', '-')));
+
+ set = CharSet.getInstance("--a");
+ array = set.getCharRanges();
+ assertEquals(1, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('-', 'a')));
+ }
+
+ public void testConstructor_String_oddNegate() {
+ CharSet set;
+ CharRange[] array;
+ set = CharSet.getInstance("^");
+ array = set.getCharRanges();
+ assertEquals(1, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('^'))); // "^"
+
+ set = CharSet.getInstance("^^");
+ array = set.getCharRanges();
+ assertEquals(1, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('^'))); // "^^"
+
+ set = CharSet.getInstance("^^^");
+ array = set.getCharRanges();
+ assertEquals(2, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('^'))); // "^^"
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('^'))); // "^"
+
+ set = CharSet.getInstance("^^^^");
+ array = set.getCharRanges();
+ assertEquals(1, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('^'))); // "^^" x2
+
+ set = CharSet.getInstance("a^");
+ array = set.getCharRanges();
+ assertEquals(2, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('a'))); // "a"
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('^'))); // "^"
+
+ set = CharSet.getInstance("^a-");
+ array = set.getCharRanges();
+ assertEquals(2, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('a'))); // "^a"
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('-'))); // "-"
+
+ set = CharSet.getInstance("^^-c");
+ array = set.getCharRanges();
+ assertEquals(1, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isNotIn('^', 'c'))); // "^^-c"
+
+ set = CharSet.getInstance("^c-^");
+ array = set.getCharRanges();
+ assertEquals(1, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isNotIn('c', '^'))); // "^c-^"
+
+ set = CharSet.getInstance("^c-^d");
+ array = set.getCharRanges();
+ assertEquals(2, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isNotIn('c', '^'))); // "^c-^"
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('d'))); // "d"
+
+ set = CharSet.getInstance("^^-");
+ array = set.getCharRanges();
+ assertEquals(2, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('^'))); // "^^"
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('-'))); // "-"
+ }
+
+ public void testConstructor_String_oddCombinations() {
+ CharSet set;
+ CharRange[] array = null;
+
+ set = CharSet.getInstance("a-^c");
+ array = set.getCharRanges();
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('a', '^'))); // "a-^"
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('c'))); // "c"
+ assertEquals(false, set.contains('b'));
+ assertEquals(true, set.contains('^'));
+ assertEquals(true, set.contains('_')); // between ^ and a
+ assertEquals(true, set.contains('c'));
+
+ set = CharSet.getInstance("^a-^c");
+ array = set.getCharRanges();
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isNotIn('a', '^'))); // "^a-^"
+ assertEquals(true, ArrayUtils.contains(array, CharRange.is('c'))); // "c"
+ assertEquals(true, set.contains('b'));
+ assertEquals(false, set.contains('^'));
+ assertEquals(false, set.contains('_')); // between ^ and a
+
+ set = CharSet.getInstance("a- ^-- "); //contains everything
+ array = set.getCharRanges();
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('a', ' '))); // "a- "
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isNotIn('-', ' '))); // "^-- "
+ assertEquals(true, set.contains('#'));
+ assertEquals(true, set.contains('^'));
+ assertEquals(true, set.contains('a'));
+ assertEquals(true, set.contains('*'));
+ assertEquals(true, set.contains('A'));
+
+ set = CharSet.getInstance("^-b");
+ array = set.getCharRanges();
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('^','b'))); // "^-b"
+ assertEquals(true, set.contains('b'));
+ assertEquals(true, set.contains('_')); // between ^ and a
+ assertEquals(false, set.contains('A'));
+ assertEquals(true, set.contains('^'));
+
+ set = CharSet.getInstance("b-^");
+ array = set.getCharRanges();
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('^','b'))); // "b-^"
+ assertEquals(true, set.contains('b'));
+ assertEquals(true, set.contains('^'));
+ assertEquals(true, set.contains('a')); // between ^ and b
+ assertEquals(false, set.contains('c'));
+ }
+
+ //-----------------------------------------------------------------------
+ public void testEquals_Object() {
+ CharSet abc = CharSet.getInstance("abc");
+ CharSet abc2 = CharSet.getInstance("abc");
+ CharSet atoc = CharSet.getInstance("a-c");
+ CharSet atoc2 = CharSet.getInstance("a-c");
+ CharSet notatoc = CharSet.getInstance("^a-c");
+ CharSet notatoc2 = CharSet.getInstance("^a-c");
+
+ assertEquals(false, abc.equals(null));
+
+ assertEquals(true, abc.equals(abc));
+ assertEquals(true, abc.equals(abc2));
+ assertEquals(false, abc.equals(atoc));
+ assertEquals(false, abc.equals(notatoc));
+
+ assertEquals(false, atoc.equals(abc));
+ assertEquals(true, atoc.equals(atoc));
+ assertEquals(true, atoc.equals(atoc2));
+ assertEquals(false, atoc.equals(notatoc));
+
+ assertEquals(false, notatoc.equals(abc));
+ assertEquals(false, notatoc.equals(atoc));
+ assertEquals(true, notatoc.equals(notatoc));
+ assertEquals(true, notatoc.equals(notatoc2));
+ }
+
+ public void testHashCode() {
+ CharSet abc = CharSet.getInstance("abc");
+ CharSet abc2 = CharSet.getInstance("abc");
+ CharSet atoc = CharSet.getInstance("a-c");
+ CharSet atoc2 = CharSet.getInstance("a-c");
+ CharSet notatoc = CharSet.getInstance("^a-c");
+ CharSet notatoc2 = CharSet.getInstance("^a-c");
+
+ assertEquals(abc.hashCode(), abc.hashCode());
+ assertEquals(abc.hashCode(), abc2.hashCode());
+ assertEquals(atoc.hashCode(), atoc.hashCode());
+ assertEquals(atoc.hashCode(), atoc2.hashCode());
+ assertEquals(notatoc.hashCode(), notatoc.hashCode());
+ assertEquals(notatoc.hashCode(), notatoc2.hashCode());
+ }
+
+ //-----------------------------------------------------------------------
+ public void testContains_Char() {
+ CharSet btod = CharSet.getInstance("b-d");
+ CharSet dtob = CharSet.getInstance("d-b");
+ CharSet bcd = CharSet.getInstance("bcd");
+ CharSet bd = CharSet.getInstance("bd");
+ CharSet notbtod = CharSet.getInstance("^b-d");
+
+ assertEquals(false, btod.contains('a'));
+ assertEquals(true, btod.contains('b'));
+ assertEquals(true, btod.contains('c'));
+ assertEquals(true, btod.contains('d'));
+ assertEquals(false, btod.contains('e'));
+
+ assertEquals(false, bcd.contains('a'));
+ assertEquals(true, bcd.contains('b'));
+ assertEquals(true, bcd.contains('c'));
+ assertEquals(true, bcd.contains('d'));
+ assertEquals(false, bcd.contains('e'));
+
+ assertEquals(false, bd.contains('a'));
+ assertEquals(true, bd.contains('b'));
+ assertEquals(false, bd.contains('c'));
+ assertEquals(true, bd.contains('d'));
+ assertEquals(false, bd.contains('e'));
+
+ assertEquals(true, notbtod.contains('a'));
+ assertEquals(false, notbtod.contains('b'));
+ assertEquals(false, notbtod.contains('c'));
+ assertEquals(false, notbtod.contains('d'));
+ assertEquals(true, notbtod.contains('e'));
+
+ assertEquals(false, dtob.contains('a'));
+ assertEquals(true, dtob.contains('b'));
+ assertEquals(true, dtob.contains('c'));
+ assertEquals(true, dtob.contains('d'));
+ assertEquals(false, dtob.contains('e'));
+
+ CharRange[] array = dtob.getCharRanges();
+ assertEquals("[b-d]", dtob.toString());
+ assertEquals(1, array.length);
+ }
+
+ //-----------------------------------------------------------------------
+ public void testSerialization() {
+ CharSet set = CharSet.getInstance("a");
+ assertEquals(set, SerializationUtils.clone(set));
+ set = CharSet.getInstance("a-e");
+ assertEquals(set, SerializationUtils.clone(set));
+ set = CharSet.getInstance("be-f^a-z");
+ assertEquals(set, SerializationUtils.clone(set));
+ }
+
+ //-----------------------------------------------------------------------
+ public void testStatics() {
+ CharRange[] array;
+
+ array = CharSet.EMPTY.getCharRanges();
+ assertEquals(0, array.length);
+
+ array = CharSet.ASCII_ALPHA.getCharRanges();
+ assertEquals(2, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('a', 'z')));
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('A', 'Z')));
+
+ array = CharSet.ASCII_ALPHA_LOWER.getCharRanges();
+ assertEquals(1, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('a', 'z')));
+
+ array = CharSet.ASCII_ALPHA_UPPER.getCharRanges();
+ assertEquals(1, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('A', 'Z')));
+
+ array = CharSet.ASCII_NUMERIC.getCharRanges();
+ assertEquals(1, array.length);
+ assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('0', '9')));
+ }
+
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/CharSetUtils.java b/ApacheCommonsLang/org/apache/commons/lang3/CharSetUtils.java
new file mode 100644
index 0000000..2b66f9d
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/CharSetUtils.java
@@ -0,0 +1,217 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+package org.apache.commons.lang3;
+
+/**
+ * Operations on {@code CharSet} instances.
+ *
+ * This class handles {@code null} input gracefully.
+ * An exception will not be thrown for a {@code null} input.
+ * Each method documents its behaviour in more detail.
+ *
+ * #ThreadSafe#
+ * @see CharSet
+ * @since 1.0
+ * @version $Id: CharSetUtils.java 1299411 2012-03-11 17:55:29Z ggregory $
+ */
+public class CharSetUtils {
+
+ /**
+ * CharSetUtils instances should NOT be constructed in standard programming.
+ * Instead, the class should be used as {@code CharSetUtils.evaluateSet(null);}.
+ *
+ * This constructor is public to permit tools that require a JavaBean instance
+ * to operate.
+ */
+ public CharSetUtils() {
+ super();
+ }
+
+ // Squeeze
+ //-----------------------------------------------------------------------
+ /**
+ * Squeezes any repetitions of a character that is mentioned in the
+ * supplied set.
+ *
+ *
+ * CharSetUtils.squeeze(null, *) = null
+ * CharSetUtils.squeeze("", *) = ""
+ * CharSetUtils.squeeze(*, null) = *
+ * CharSetUtils.squeeze(*, "") = *
+ * CharSetUtils.squeeze("hello", "k-p") = "helo"
+ * CharSetUtils.squeeze("hello", "a-e") = "hello"
+ *
+ *
+ * @see CharSet#getInstance(java.lang.String...) for set-syntax.
+ * @param str the string to squeeze, may be null
+ * @param set the character set to use for manipulation, may be null
+ * @return the modified String, {@code null} if null string input
+ */
+ public static String squeeze(String str, String... set) {
+ if (StringUtils.isEmpty(str) || deepEmpty(set)) {
+ return str;
+ }
+ CharSet chars = CharSet.getInstance(set);
+ StringBuilder buffer = new StringBuilder(str.length());
+ char[] chrs = str.toCharArray();
+ int sz = chrs.length;
+ char lastChar = ' ';
+ char ch = ' ';
+ for (int i = 0; i < sz; i++) {
+ ch = chrs[i];
+ // Compare with contains() last for performance.
+ if (ch == lastChar && i != 0 && chars.contains(ch)) {
+ continue;
+ }
+ buffer.append(ch);
+ lastChar = ch;
+ }
+ return buffer.toString();
+ }
+
+ // Count
+ //-----------------------------------------------------------------------
+ /**
+ * Takes an argument in set-syntax, see evaluateSet,
+ * and returns the number of characters present in the specified string.
+ *
+ *
+ * CharSetUtils.count(null, *) = 0
+ * CharSetUtils.count("", *) = 0
+ * CharSetUtils.count(*, null) = 0
+ * CharSetUtils.count(*, "") = 0
+ * CharSetUtils.count("hello", "k-p") = 3
+ * CharSetUtils.count("hello", "a-e") = 1
+ *
+ *
+ * @see CharSet#getInstance(java.lang.String...) for set-syntax.
+ * @param str String to count characters in, may be null
+ * @param set String[] set of characters to count, may be null
+ * @return the character count, zero if null string input
+ */
+ public static int count(String str, String... set) {
+ if (StringUtils.isEmpty(str) || deepEmpty(set)) {
+ return 0;
+ }
+ CharSet chars = CharSet.getInstance(set);
+ int count = 0;
+ for (char c : str.toCharArray()) {
+ if (chars.contains(c)) {
+ count++;
+ }
+ }
+ return count;
+ }
+
+ // Keep
+ //-----------------------------------------------------------------------
+ /**
+ * Takes an argument in set-syntax, see evaluateSet,
+ * and keeps any of characters present in the specified string.
+ *
+ *
+ * CharSetUtils.keep(null, *) = null
+ * CharSetUtils.keep("", *) = ""
+ * CharSetUtils.keep(*, null) = ""
+ * CharSetUtils.keep(*, "") = ""
+ * CharSetUtils.keep("hello", "hl") = "hll"
+ * CharSetUtils.keep("hello", "le") = "ell"
+ *
+ *
+ * @see CharSet#getInstance(java.lang.String...) for set-syntax.
+ * @param str String to keep characters from, may be null
+ * @param set String[] set of characters to keep, may be null
+ * @return the modified String, {@code null} if null string input
+ * @since 2.0
+ */
+ public static String keep(String str, String... set) {
+ if (str == null) {
+ return null;
+ }
+ if (str.length() == 0 || deepEmpty(set)) {
+ return StringUtils.EMPTY;
+ }
+ return modify(str, set, true);
+ }
+
+ // Delete
+ //-----------------------------------------------------------------------
+ /**
+ * Takes an argument in set-syntax, see evaluateSet,
+ * and deletes any of characters present in the specified string.
+ *
+ *
+ * CharSetUtils.delete(null, *) = null
+ * CharSetUtils.delete("", *) = ""
+ * CharSetUtils.delete(*, null) = *
+ * CharSetUtils.delete(*, "") = *
+ * CharSetUtils.delete("hello", "hl") = "eo"
+ * CharSetUtils.delete("hello", "le") = "ho"
+ *
+ *
+ * @see CharSet#getInstance(java.lang.String...) for set-syntax.
+ * @param str String to delete characters from, may be null
+ * @param set String[] set of characters to delete, may be null
+ * @return the modified String, {@code null} if null string input
+ */
+ public static String delete(String str, String... set) {
+ if (StringUtils.isEmpty(str) || deepEmpty(set)) {
+ return str;
+ }
+ return modify(str, set, false);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Implementation of delete and keep
+ *
+ * @param str String to modify characters within
+ * @param set String[] set of characters to modify
+ * @param expect whether to evaluate on match, or non-match
+ * @return the modified String, not null
+ */
+ private static String modify(String str, String[] set, boolean expect) {
+ CharSet chars = CharSet.getInstance(set);
+ StringBuilder buffer = new StringBuilder(str.length());
+ char[] chrs = str.toCharArray();
+ int sz = chrs.length;
+ for(int i=0; i[] cons = CharSetUtils.class.getDeclaredConstructors();
+ assertEquals(1, cons.length);
+ assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
+ assertEquals(true, Modifier.isPublic(CharSetUtils.class.getModifiers()));
+ assertEquals(false, Modifier.isFinal(CharSetUtils.class.getModifiers()));
+ }
+
+ //-----------------------------------------------------------------------
+ public void testSqueeze_StringString() {
+ assertEquals(null, CharSetUtils.squeeze(null, (String) null));
+ assertEquals(null, CharSetUtils.squeeze(null, ""));
+
+ assertEquals("", CharSetUtils.squeeze("", (String) null));
+ assertEquals("", CharSetUtils.squeeze("", ""));
+ assertEquals("", CharSetUtils.squeeze("", "a-e"));
+
+ assertEquals("hello", CharSetUtils.squeeze("hello", (String) null));
+ assertEquals("hello", CharSetUtils.squeeze("hello", ""));
+ assertEquals("hello", CharSetUtils.squeeze("hello", "a-e"));
+ assertEquals("helo", CharSetUtils.squeeze("hello", "l-p"));
+ assertEquals("heloo", CharSetUtils.squeeze("helloo", "l"));
+ assertEquals("hello", CharSetUtils.squeeze("helloo", "^l"));
+ }
+
+ public void testSqueeze_StringStringarray() {
+ assertEquals(null, CharSetUtils.squeeze(null, (String[]) null));
+ assertEquals(null, CharSetUtils.squeeze(null, new String[0]));
+ assertEquals(null, CharSetUtils.squeeze(null, new String[] {null}));
+ assertEquals(null, CharSetUtils.squeeze(null, new String[] {"el"}));
+
+ assertEquals("", CharSetUtils.squeeze("", (String[]) null));
+ assertEquals("", CharSetUtils.squeeze("", new String[0]));
+ assertEquals("", CharSetUtils.squeeze("", new String[] {null}));
+ assertEquals("", CharSetUtils.squeeze("", new String[] {"a-e"}));
+
+ assertEquals("hello", CharSetUtils.squeeze("hello", (String[]) null));
+ assertEquals("hello", CharSetUtils.squeeze("hello", new String[0]));
+ assertEquals("hello", CharSetUtils.squeeze("hello", new String[] {null}));
+ assertEquals("hello", CharSetUtils.squeeze("hello", new String[] {"a-e"}));
+
+ assertEquals("helo", CharSetUtils.squeeze("hello", new String[] { "el" }));
+ assertEquals("hello", CharSetUtils.squeeze("hello", new String[] { "e" }));
+ assertEquals("fofof", CharSetUtils.squeeze("fooffooff", new String[] { "of" }));
+ assertEquals("fof", CharSetUtils.squeeze("fooooff", new String[] { "fo" }));
+ }
+
+ //-----------------------------------------------------------------------
+ public void testCount_StringString() {
+ assertEquals(0, CharSetUtils.count(null, (String) null));
+ assertEquals(0, CharSetUtils.count(null, ""));
+
+ assertEquals(0, CharSetUtils.count("", (String) null));
+ assertEquals(0, CharSetUtils.count("", ""));
+ assertEquals(0, CharSetUtils.count("", "a-e"));
+
+ assertEquals(0, CharSetUtils.count("hello", (String) null));
+ assertEquals(0, CharSetUtils.count("hello", ""));
+ assertEquals(1, CharSetUtils.count("hello", "a-e"));
+ assertEquals(3, CharSetUtils.count("hello", "l-p"));
+ }
+
+ public void testCount_StringStringarray() {
+ assertEquals(0, CharSetUtils.count(null, (String[]) null));
+ assertEquals(0, CharSetUtils.count(null, new String[0]));
+ assertEquals(0, CharSetUtils.count(null, new String[] {null}));
+ assertEquals(0, CharSetUtils.count(null, new String[] {"a-e"}));
+
+ assertEquals(0, CharSetUtils.count("", (String[]) null));
+ assertEquals(0, CharSetUtils.count("", new String[0]));
+ assertEquals(0, CharSetUtils.count("", new String[] {null}));
+ assertEquals(0, CharSetUtils.count("", new String[] {"a-e"}));
+
+ assertEquals(0, CharSetUtils.count("hello", (String[]) null));
+ assertEquals(0, CharSetUtils.count("hello", new String[0]));
+ assertEquals(0, CharSetUtils.count("hello", new String[] {null}));
+ assertEquals(1, CharSetUtils.count("hello", new String[] {"a-e"}));
+
+ assertEquals(3, CharSetUtils.count("hello", new String[] { "el" }));
+ assertEquals(0, CharSetUtils.count("hello", new String[] { "x" }));
+ assertEquals(2, CharSetUtils.count("hello", new String[] { "e-i" }));
+ assertEquals(5, CharSetUtils.count("hello", new String[] { "a-z" }));
+ assertEquals(0, CharSetUtils.count("hello", new String[] { "" }));
+ }
+
+ //-----------------------------------------------------------------------
+ public void testKeep_StringString() {
+ assertEquals(null, CharSetUtils.keep(null, (String) null));
+ assertEquals(null, CharSetUtils.keep(null, ""));
+
+ assertEquals("", CharSetUtils.keep("", (String) null));
+ assertEquals("", CharSetUtils.keep("", ""));
+ assertEquals("", CharSetUtils.keep("", "a-e"));
+
+ assertEquals("", CharSetUtils.keep("hello", (String) null));
+ assertEquals("", CharSetUtils.keep("hello", ""));
+ assertEquals("", CharSetUtils.keep("hello", "xyz"));
+ assertEquals("hello", CharSetUtils.keep("hello", "a-z"));
+ assertEquals("hello", CharSetUtils.keep("hello", "oleh"));
+ assertEquals("ell", CharSetUtils.keep("hello", "el"));
+ }
+
+ public void testKeep_StringStringarray() {
+ assertEquals(null, CharSetUtils.keep(null, (String[]) null));
+ assertEquals(null, CharSetUtils.keep(null, new String[0]));
+ assertEquals(null, CharSetUtils.keep(null, new String[] {null}));
+ assertEquals(null, CharSetUtils.keep(null, new String[] {"a-e"}));
+
+ assertEquals("", CharSetUtils.keep("", (String[]) null));
+ assertEquals("", CharSetUtils.keep("", new String[0]));
+ assertEquals("", CharSetUtils.keep("", new String[] {null}));
+ assertEquals("", CharSetUtils.keep("", new String[] {"a-e"}));
+
+ assertEquals("", CharSetUtils.keep("hello", (String[]) null));
+ assertEquals("", CharSetUtils.keep("hello", new String[0]));
+ assertEquals("", CharSetUtils.keep("hello", new String[] {null}));
+ assertEquals("e", CharSetUtils.keep("hello", new String[] {"a-e"}));
+
+ assertEquals("e", CharSetUtils.keep("hello", new String[] { "a-e" }));
+ assertEquals("ell", CharSetUtils.keep("hello", new String[] { "el" }));
+ assertEquals("hello", CharSetUtils.keep("hello", new String[] { "elho" }));
+ assertEquals("hello", CharSetUtils.keep("hello", new String[] { "a-z" }));
+ assertEquals("----", CharSetUtils.keep("----", new String[] { "-" }));
+ assertEquals("ll", CharSetUtils.keep("hello", new String[] { "l" }));
+ }
+
+ //-----------------------------------------------------------------------
+ public void testDelete_StringString() {
+ assertEquals(null, CharSetUtils.delete(null, (String) null));
+ assertEquals(null, CharSetUtils.delete(null, ""));
+
+ assertEquals("", CharSetUtils.delete("", (String) null));
+ assertEquals("", CharSetUtils.delete("", ""));
+ assertEquals("", CharSetUtils.delete("", "a-e"));
+
+ assertEquals("hello", CharSetUtils.delete("hello", (String) null));
+ assertEquals("hello", CharSetUtils.delete("hello", ""));
+ assertEquals("hllo", CharSetUtils.delete("hello", "a-e"));
+ assertEquals("he", CharSetUtils.delete("hello", "l-p"));
+ assertEquals("hello", CharSetUtils.delete("hello", "z"));
+ }
+
+ public void testDelete_StringStringarray() {
+ assertEquals(null, CharSetUtils.delete(null, (String[]) null));
+ assertEquals(null, CharSetUtils.delete(null, new String[0]));
+ assertEquals(null, CharSetUtils.delete(null, new String[] {null}));
+ assertEquals(null, CharSetUtils.delete(null, new String[] {"el"}));
+
+ assertEquals("", CharSetUtils.delete("", (String[]) null));
+ assertEquals("", CharSetUtils.delete("", new String[0]));
+ assertEquals("", CharSetUtils.delete("", new String[] {null}));
+ assertEquals("", CharSetUtils.delete("", new String[] {"a-e"}));
+
+ assertEquals("hello", CharSetUtils.delete("hello", (String[]) null));
+ assertEquals("hello", CharSetUtils.delete("hello", new String[0]));
+ assertEquals("hello", CharSetUtils.delete("hello", new String[] {null}));
+ assertEquals("hello", CharSetUtils.delete("hello", new String[] {"xyz"}));
+
+ assertEquals("ho", CharSetUtils.delete("hello", new String[] { "el" }));
+ assertEquals("", CharSetUtils.delete("hello", new String[] { "elho" }));
+ assertEquals("hello", CharSetUtils.delete("hello", new String[] { "" }));
+ assertEquals("hello", CharSetUtils.delete("hello", ""));
+ assertEquals("", CharSetUtils.delete("hello", new String[] { "a-z" }));
+ assertEquals("", CharSetUtils.delete("----", new String[] { "-" }));
+ assertEquals("heo", CharSetUtils.delete("hello", new String[] { "l" }));
+ }
+
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/CharUtils.java b/ApacheCommonsLang/org/apache/commons/lang3/CharUtils.java
new file mode 100644
index 0000000..7ce2d60
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/CharUtils.java
@@ -0,0 +1,539 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+package org.apache.commons.lang3;
+
+/**
+ * Operations on char primitives and Character objects.
+ *
+ * This class tries to handle {@code null} input gracefully.
+ * An exception will not be thrown for a {@code null} input.
+ * Each method documents its behaviour in more detail.
+ *
+ * #ThreadSafe#
+ * @since 2.1
+ * @version $Id: CharUtils.java 1158279 2011-08-16 14:06:45Z ggregory $
+ */
+public class CharUtils {
+
+ private static final String[] CHAR_STRING_ARRAY = new String[128];
+
+ /**
+ * {@code \u000a} linefeed LF ('\n').
+ *
+ * @see JLF: Escape Sequences
+ * for Character and String Literals
+ * @since 2.2
+ */
+ public static final char LF = '\n';
+
+ /**
+ * {@code \u000d} carriage return CR ('\r').
+ *
+ * @see JLF: Escape Sequences
+ * for Character and String Literals
+ * @since 2.2
+ */
+ public static final char CR = '\r';
+
+
+ static {
+ for (char c = 0; c < CHAR_STRING_ARRAY.length; c++) {
+ CHAR_STRING_ARRAY[c] = String.valueOf(c);
+ }
+ }
+
+ /**
+ * {@code CharUtils} instances should NOT be constructed in standard programming.
+ * Instead, the class should be used as {@code CharUtils.toString('c');}.
+ *
+ * This constructor is public to permit tools that require a JavaBean instance
+ * to operate.
+ */
+ public CharUtils() {
+ super();
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Converts the character to a Character.
+ *
+ * For ASCII 7 bit characters, this uses a cache that will return the
+ * same Character object each time.
+ *
+ *
+ * CharUtils.toCharacterObject(' ') = ' '
+ * CharUtils.toCharacterObject('A') = 'A'
+ *
+ *
+ * @deprecated Java 5 introduced {@link Character#valueOf(char)} which caches chars 0 through 127.
+ * @param ch the character to convert
+ * @return a Character of the specified character
+ */
+ @Deprecated
+ public static Character toCharacterObject(char ch) {
+ return Character.valueOf(ch);
+ }
+
+ /**
+ * Converts the String to a Character using the first character, returning
+ * null for empty Strings.
+ *
+ * For ASCII 7 bit characters, this uses a cache that will return the
+ * same Character object each time.
+ *
+ *
+ * CharUtils.toCharacterObject(null) = null
+ * CharUtils.toCharacterObject("") = null
+ * CharUtils.toCharacterObject("A") = 'A'
+ * CharUtils.toCharacterObject("BA") = 'B'
+ *
+ *
+ * @param str the character to convert
+ * @return the Character value of the first letter of the String
+ */
+ public static Character toCharacterObject(String str) {
+ if (StringUtils.isEmpty(str)) {
+ return null;
+ }
+ return Character.valueOf(str.charAt(0));
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Converts the Character to a char throwing an exception for {@code null}.
+ *
+ *
+ * CharUtils.toChar(' ') = ' '
+ * CharUtils.toChar('A') = 'A'
+ * CharUtils.toChar(null) throws IllegalArgumentException
+ *
+ *
+ * @param ch the character to convert
+ * @return the char value of the Character
+ * @throws IllegalArgumentException if the Character is null
+ */
+ public static char toChar(Character ch) {
+ if (ch == null) {
+ throw new IllegalArgumentException("The Character must not be null");
+ }
+ return ch.charValue();
+ }
+
+ /**
+ * Converts the Character to a char handling {@code null}.
+ *
+ *
+ * CharUtils.toChar(null, 'X') = 'X'
+ * CharUtils.toChar(' ', 'X') = ' '
+ * CharUtils.toChar('A', 'X') = 'A'
+ *
+ *
+ * @param ch the character to convert
+ * @param defaultValue the value to use if the Character is null
+ * @return the char value of the Character or the default if null
+ */
+ public static char toChar(Character ch, char defaultValue) {
+ if (ch == null) {
+ return defaultValue;
+ }
+ return ch.charValue();
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Converts the String to a char using the first character, throwing
+ * an exception on empty Strings.
+ *
+ *
+ * CharUtils.toChar("A") = 'A'
+ * CharUtils.toChar("BA") = 'B'
+ * CharUtils.toChar(null) throws IllegalArgumentException
+ * CharUtils.toChar("") throws IllegalArgumentException
+ *
+ *
+ * @param str the character to convert
+ * @return the char value of the first letter of the String
+ * @throws IllegalArgumentException if the String is empty
+ */
+ public static char toChar(String str) {
+ if (StringUtils.isEmpty(str)) {
+ throw new IllegalArgumentException("The String must not be empty");
+ }
+ return str.charAt(0);
+ }
+
+ /**
+ * Converts the String to a char using the first character, defaulting
+ * the value on empty Strings.
+ *
+ *
+ * CharUtils.toChar(null, 'X') = 'X'
+ * CharUtils.toChar("", 'X') = 'X'
+ * CharUtils.toChar("A", 'X') = 'A'
+ * CharUtils.toChar("BA", 'X') = 'B'
+ *
+ *
+ * @param str the character to convert
+ * @param defaultValue the value to use if the Character is null
+ * @return the char value of the first letter of the String or the default if null
+ */
+ public static char toChar(String str, char defaultValue) {
+ if (StringUtils.isEmpty(str)) {
+ return defaultValue;
+ }
+ return str.charAt(0);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Converts the character to the Integer it represents, throwing an
+ * exception if the character is not numeric.
+ *
+ * This method coverts the char '1' to the int 1 and so on.
+ *
+ *
+ * CharUtils.toIntValue('3') = 3
+ * CharUtils.toIntValue('A') throws IllegalArgumentException
+ *
+ *
+ * @param ch the character to convert
+ * @return the int value of the character
+ * @throws IllegalArgumentException if the character is not ASCII numeric
+ */
+ public static int toIntValue(char ch) {
+ if (isAsciiNumeric(ch) == false) {
+ throw new IllegalArgumentException("The character " + ch + " is not in the range '0' - '9'");
+ }
+ return ch - 48;
+ }
+
+ /**
+ * Converts the character to the Integer it represents, throwing an
+ * exception if the character is not numeric.
+ *
+ * This method coverts the char '1' to the int 1 and so on.
+ *
+ *
+ * CharUtils.toIntValue('3', -1) = 3
+ * CharUtils.toIntValue('A', -1) = -1
+ *
+ *
+ * @param ch the character to convert
+ * @param defaultValue the default value to use if the character is not numeric
+ * @return the int value of the character
+ */
+ public static int toIntValue(char ch, int defaultValue) {
+ if (isAsciiNumeric(ch) == false) {
+ return defaultValue;
+ }
+ return ch - 48;
+ }
+
+ /**
+ * Converts the character to the Integer it represents, throwing an
+ * exception if the character is not numeric.
+ *
+ * This method coverts the char '1' to the int 1 and so on.
+ *
+ *
+ * CharUtils.toIntValue('3') = 3
+ * CharUtils.toIntValue(null) throws IllegalArgumentException
+ * CharUtils.toIntValue('A') throws IllegalArgumentException
+ *
+ *
+ * @param ch the character to convert, not null
+ * @return the int value of the character
+ * @throws IllegalArgumentException if the Character is not ASCII numeric or is null
+ */
+ public static int toIntValue(Character ch) {
+ if (ch == null) {
+ throw new IllegalArgumentException("The character must not be null");
+ }
+ return toIntValue(ch.charValue());
+ }
+
+ /**
+ * Converts the character to the Integer it represents, throwing an
+ * exception if the character is not numeric.
+ *
+ * This method coverts the char '1' to the int 1 and so on.
+ *
+ *
+ * CharUtils.toIntValue(null, -1) = -1
+ * CharUtils.toIntValue('3', -1) = 3
+ * CharUtils.toIntValue('A', -1) = -1
+ *
+ *
+ * @param ch the character to convert
+ * @param defaultValue the default value to use if the character is not numeric
+ * @return the int value of the character
+ */
+ public static int toIntValue(Character ch, int defaultValue) {
+ if (ch == null) {
+ return defaultValue;
+ }
+ return toIntValue(ch.charValue(), defaultValue);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Converts the character to a String that contains the one character.
+ *
+ * For ASCII 7 bit characters, this uses a cache that will return the
+ * same String object each time.
+ *
+ *
+ * CharUtils.toString(' ') = " "
+ * CharUtils.toString('A') = "A"
+ *
+ *
+ * @param ch the character to convert
+ * @return a String containing the one specified character
+ */
+ public static String toString(char ch) {
+ if (ch < 128) {
+ return CHAR_STRING_ARRAY[ch];
+ }
+ return new String(new char[] {ch});
+ }
+
+ /**
+ * Converts the character to a String that contains the one character.
+ *
+ * For ASCII 7 bit characters, this uses a cache that will return the
+ * same String object each time.
+ *
+ * If {@code null} is passed in, {@code null} will be returned.
+ *
+ *
+ * CharUtils.toString(null) = null
+ * CharUtils.toString(' ') = " "
+ * CharUtils.toString('A') = "A"
+ *
+ *
+ * @param ch the character to convert
+ * @return a String containing the one specified character
+ */
+ public static String toString(Character ch) {
+ if (ch == null) {
+ return null;
+ }
+ return toString(ch.charValue());
+ }
+
+ //--------------------------------------------------------------------------
+ /**
+ * Converts the string to the Unicode format '\u0020'.
+ *
+ * This format is the Java source code format.
+ *
+ *
+ * CharUtils.unicodeEscaped(' ') = "\u0020"
+ * CharUtils.unicodeEscaped('A') = "\u0041"
+ *
+ *
+ * @param ch the character to convert
+ * @return the escaped Unicode string
+ */
+ public static String unicodeEscaped(char ch) {
+ if (ch < 0x10) {
+ return "\\u000" + Integer.toHexString(ch);
+ } else if (ch < 0x100) {
+ return "\\u00" + Integer.toHexString(ch);
+ } else if (ch < 0x1000) {
+ return "\\u0" + Integer.toHexString(ch);
+ }
+ return "\\u" + Integer.toHexString(ch);
+ }
+
+ /**
+ * Converts the string to the Unicode format '\u0020'.
+ *
+ * This format is the Java source code format.
+ *
+ * If {@code null} is passed in, {@code null} will be returned.
+ *
+ *
+ * CharUtils.unicodeEscaped(null) = null
+ * CharUtils.unicodeEscaped(' ') = "\u0020"
+ * CharUtils.unicodeEscaped('A') = "\u0041"
+ *
+ *
+ * @param ch the character to convert, may be null
+ * @return the escaped Unicode string, null if null input
+ */
+ public static String unicodeEscaped(Character ch) {
+ if (ch == null) {
+ return null;
+ }
+ return unicodeEscaped(ch.charValue());
+ }
+
+ //--------------------------------------------------------------------------
+ /**
+ * Checks whether the character is ASCII 7 bit.
+ *
+ *
+ * CharUtils.isAscii('a') = true
+ * CharUtils.isAscii('A') = true
+ * CharUtils.isAscii('3') = true
+ * CharUtils.isAscii('-') = true
+ * CharUtils.isAscii('\n') = true
+ * CharUtils.isAscii('©') = false
+ *
+ *
+ * @param ch the character to check
+ * @return true if less than 128
+ */
+ public static boolean isAscii(char ch) {
+ return ch < 128;
+ }
+
+ /**
+ * Checks whether the character is ASCII 7 bit printable.
+ *
+ *
+ * CharUtils.isAsciiPrintable('a') = true
+ * CharUtils.isAsciiPrintable('A') = true
+ * CharUtils.isAsciiPrintable('3') = true
+ * CharUtils.isAsciiPrintable('-') = true
+ * CharUtils.isAsciiPrintable('\n') = false
+ * CharUtils.isAsciiPrintable('©') = false
+ *
+ *
+ * @param ch the character to check
+ * @return true if between 32 and 126 inclusive
+ */
+ public static boolean isAsciiPrintable(char ch) {
+ return ch >= 32 && ch < 127;
+ }
+
+ /**
+ * Checks whether the character is ASCII 7 bit control.
+ *
+ *
+ * CharUtils.isAsciiControl('a') = false
+ * CharUtils.isAsciiControl('A') = false
+ * CharUtils.isAsciiControl('3') = false
+ * CharUtils.isAsciiControl('-') = false
+ * CharUtils.isAsciiControl('\n') = true
+ * CharUtils.isAsciiControl('©') = false
+ *
+ *
+ * @param ch the character to check
+ * @return true if less than 32 or equals 127
+ */
+ public static boolean isAsciiControl(char ch) {
+ return ch < 32 || ch == 127;
+ }
+
+ /**
+ * Checks whether the character is ASCII 7 bit alphabetic.
+ *
+ *
+ * CharUtils.isAsciiAlpha('a') = true
+ * CharUtils.isAsciiAlpha('A') = true
+ * CharUtils.isAsciiAlpha('3') = false
+ * CharUtils.isAsciiAlpha('-') = false
+ * CharUtils.isAsciiAlpha('\n') = false
+ * CharUtils.isAsciiAlpha('©') = false
+ *
+ *
+ * @param ch the character to check
+ * @return true if between 65 and 90 or 97 and 122 inclusive
+ */
+ public static boolean isAsciiAlpha(char ch) {
+ return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z');
+ }
+
+ /**
+ * Checks whether the character is ASCII 7 bit alphabetic upper case.
+ *
+ *
+ * CharUtils.isAsciiAlphaUpper('a') = false
+ * CharUtils.isAsciiAlphaUpper('A') = true
+ * CharUtils.isAsciiAlphaUpper('3') = false
+ * CharUtils.isAsciiAlphaUpper('-') = false
+ * CharUtils.isAsciiAlphaUpper('\n') = false
+ * CharUtils.isAsciiAlphaUpper('©') = false
+ *
+ *
+ * @param ch the character to check
+ * @return true if between 65 and 90 inclusive
+ */
+ public static boolean isAsciiAlphaUpper(char ch) {
+ return ch >= 'A' && ch <= 'Z';
+ }
+
+ /**
+ * Checks whether the character is ASCII 7 bit alphabetic lower case.
+ *
+ *
+ * CharUtils.isAsciiAlphaLower('a') = true
+ * CharUtils.isAsciiAlphaLower('A') = false
+ * CharUtils.isAsciiAlphaLower('3') = false
+ * CharUtils.isAsciiAlphaLower('-') = false
+ * CharUtils.isAsciiAlphaLower('\n') = false
+ * CharUtils.isAsciiAlphaLower('©') = false
+ *
+ *
+ * @param ch the character to check
+ * @return true if between 97 and 122 inclusive
+ */
+ public static boolean isAsciiAlphaLower(char ch) {
+ return ch >= 'a' && ch <= 'z';
+ }
+
+ /**
+ * Checks whether the character is ASCII 7 bit numeric.
+ *
+ *
+ * CharUtils.isAsciiNumeric('a') = false
+ * CharUtils.isAsciiNumeric('A') = false
+ * CharUtils.isAsciiNumeric('3') = true
+ * CharUtils.isAsciiNumeric('-') = false
+ * CharUtils.isAsciiNumeric('\n') = false
+ * CharUtils.isAsciiNumeric('©') = false
+ *
+ *
+ * @param ch the character to check
+ * @return true if between 48 and 57 inclusive
+ */
+ public static boolean isAsciiNumeric(char ch) {
+ return ch >= '0' && ch <= '9';
+ }
+
+ /**
+ * Checks whether the character is ASCII 7 bit numeric.
+ *
+ *
+ * CharUtils.isAsciiAlphanumeric('a') = true
+ * CharUtils.isAsciiAlphanumeric('A') = true
+ * CharUtils.isAsciiAlphanumeric('3') = true
+ * CharUtils.isAsciiAlphanumeric('-') = false
+ * CharUtils.isAsciiAlphanumeric('\n') = false
+ * CharUtils.isAsciiAlphanumeric('©') = false
+ *
+ *
+ * @param ch the character to check
+ * @return true if between 48 and 57 or 65 and 90 or 97 and 122 inclusive
+ */
+ public static boolean isAsciiAlphanumeric(char ch) {
+ return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9');
+ }
+
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/CharUtilsPerfRun.java b/ApacheCommonsLang/org/apache/commons/lang3/CharUtilsPerfRun.java
new file mode 100644
index 0000000..00f1232
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/CharUtilsPerfRun.java
@@ -0,0 +1,162 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+package org.apache.commons.lang3;
+
+import java.text.NumberFormat;
+import java.util.Calendar;
+
+/**
+ * Tests the difference in performance between CharUtils and CharSet.
+ *
+ * Sample runs:
+
+Now: Thu Mar 18 14:29:48 PST 2004
+Sun Microsystems Inc. Java(TM) 2 Runtime Environment, Standard Edition 1.3.1_10-b03
+Sun Microsystems Inc. Java HotSpot(TM) Client VM 1.3.1_10-b03
+Windows XP 5.1 x86 pentium i486 i386
+Do nohting: 0 milliseconds.
+run_CharUtils_isAsciiNumeric: 4,545 milliseconds.
+run_inlined_CharUtils_isAsciiNumeric: 3,417 milliseconds.
+run_inlined_CharUtils_isAsciiNumeric: 85,679 milliseconds.
+
+
+Now: Thu Mar 18 14:24:51 PST 2004
+Sun Microsystems Inc. Java(TM) 2 Runtime Environment, Standard Edition 1.4.2_04-b05
+Sun Microsystems Inc. Java HotSpot(TM) Client VM 1.4.2_04-b05
+Windows XP 5.1 x86 pentium i486 i386
+Do nohting: 0 milliseconds.
+run_CharUtils_isAsciiNumeric: 2,578 milliseconds.
+run_inlined_CharUtils_isAsciiNumeric: 2,477 milliseconds.
+run_inlined_CharUtils_isAsciiNumeric: 114,429 milliseconds.
+
+Now: Thu Mar 18 14:27:55 PST 2004
+Sun Microsystems Inc. Java(TM) 2 Runtime Environment, Standard Edition 1.4.2_04-b05
+Sun Microsystems Inc. Java HotSpot(TM) Server VM 1.4.2_04-b05
+Windows XP 5.1 x86 pentium i486 i386
+Do nohting: 0 milliseconds.
+run_CharUtils_isAsciiNumeric: 630 milliseconds.
+run_inlined_CharUtils_isAsciiNumeric: 709 milliseconds.
+run_inlined_CharUtils_isAsciiNumeric: 84,420 milliseconds.
+
+
+ * @version $Id: CharUtilsPerfRun.java 1199894 2011-11-09 17:53:59Z ggregory $
+ */
+public class CharUtilsPerfRun {
+ final static String VERSION = "$Id: CharUtilsPerfRun.java 1199894 2011-11-09 17:53:59Z ggregory $";
+
+ final static int WARM_UP = 100;
+
+ final static int COUNT = 5000;
+
+ final static char[] CHAR_SAMPLES;
+ static {
+ CHAR_SAMPLES = new char[Character.MAX_VALUE];
+ for (char i = Character.MIN_VALUE; i < Character.MAX_VALUE; i++) {
+ CHAR_SAMPLES[i] = i;
+ }
+ }
+
+ public static void main(String[] args) {
+ new CharUtilsPerfRun().run();
+ }
+
+ private void printSysInfo() {
+ System.out.println(VERSION);
+ System.out.println("Now: " + Calendar.getInstance().getTime());
+ System.out.println(System.getProperty("java.vendor")
+ + " "
+ + System.getProperty("java.runtime.name")
+ + " "
+ + System.getProperty("java.runtime.version"));
+ System.out.println(System.getProperty("java.vm.vendor")
+ + " "
+ + System.getProperty("java.vm.name")
+ + " "
+ + System.getProperty("java.vm.version"));
+ System.out.println(System.getProperty("os.name")
+ + " "
+ + System.getProperty("os.version")
+ + " "
+ + System.getProperty("os.arch")
+ + " "
+ + System.getProperty("sun.cpu.isalist"));
+ }
+
+ private void run() {
+ this.printSysInfo();
+ long start;
+ start = System.currentTimeMillis();
+ this.printlnTotal("Do nohting", start);
+ //System.out.println("Warming up...");
+ run_CharUtils_isAsciiNumeric(WARM_UP);
+ //System.out.println("Measuring...");
+ start = System.currentTimeMillis();
+ run_CharUtils_isAsciiNumeric(COUNT);
+ this.printlnTotal("run_CharUtils_isAsciiNumeric", start);
+ //System.out.println("Warming up...");
+ run_inlined_CharUtils_isAsciiNumeric(WARM_UP);
+ //System.out.println("Measuring...");
+ start = System.currentTimeMillis();
+ run_inlined_CharUtils_isAsciiNumeric(COUNT);
+ this.printlnTotal("run_inlined_CharUtils_isAsciiNumeric", start);
+ //System.out.println("Warming up...");
+ run_CharSet(WARM_UP);
+ //System.out.println("Measuring...");
+ start = System.currentTimeMillis();
+ run_CharSet(COUNT);
+ this.printlnTotal("run_CharSet", start);
+ }
+
+ private int run_CharSet(int loopCount) {
+ int t = 0;
+ for (int i = 0; i < loopCount; i++) {
+ for (char ch : CHAR_SAMPLES) {
+ boolean b = CharSet.ASCII_NUMERIC.contains(ch);
+ t += b ? 1 : 0;
+ }
+ }
+ return t;
+ }
+
+ private int run_CharUtils_isAsciiNumeric(int loopCount) {
+ int t = 0;
+ for (int i = 0; i < loopCount; i++) {
+ for (char ch : CHAR_SAMPLES) {
+ boolean b = CharUtils.isAsciiNumeric(ch);
+ t += b ? 1 : 0;
+ }
+ }
+ return t;
+ }
+
+ private int run_inlined_CharUtils_isAsciiNumeric(int loopCount) {
+ int t = 0;
+ for (int i = 0; i < loopCount; i++) {
+ for (char ch : CHAR_SAMPLES) {
+ boolean b = ch >= '0' && ch <= '9';
+ t += b ? 1 : 0;
+ }
+ }
+ return t;
+ }
+
+ private void printlnTotal(String prefix, long start) {
+ long total = System.currentTimeMillis() - start;
+ System.out.println(prefix + ": " + NumberFormat.getInstance().format(total) + " milliseconds.");
+ }
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/CharUtilsTest.java b/ApacheCommonsLang/org/apache/commons/lang3/CharUtilsTest.java
new file mode 100644
index 0000000..3de18bf
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/CharUtilsTest.java
@@ -0,0 +1,357 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+package org.apache.commons.lang3;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Modifier;
+
+import org.junit.Test;
+
+/**
+ * Unit tests {@link org.apache.commons.lang3.CharUtils}.
+ *
+ * @version $Id: CharUtilsTest.java 1199724 2011-11-09 12:51:52Z sebb $
+ */
+public class CharUtilsTest {
+
+ private static final Character CHARACTER_A = new Character('A');
+ private static final Character CHARACTER_B = new Character('B');
+ private static final char CHAR_COPY = '\u00a9';
+
+ @Test
+ public void testConstructor() {
+ assertNotNull(new CharUtils());
+ Constructor>[] cons = CharUtils.class.getDeclaredConstructors();
+ assertEquals(1, cons.length);
+ assertTrue(Modifier.isPublic(cons[0].getModifiers()));
+ assertTrue(Modifier.isPublic(BooleanUtils.class.getModifiers()));
+ assertFalse(Modifier.isFinal(BooleanUtils.class.getModifiers()));
+ }
+
+ @Test
+ public void testToCharacterObject_char() {
+ assertEquals(new Character('a'), CharUtils.toCharacterObject('a'));
+ assertSame(CharUtils.toCharacterObject('a'), CharUtils.toCharacterObject('a'));
+
+ for (int i = 0; i < 128; i++) {
+ Character ch = CharUtils.toCharacterObject((char) i);
+ Character ch2 = CharUtils.toCharacterObject((char) i);
+ assertSame(ch, ch2);
+ assertEquals(i, ch.charValue());
+ }
+ for (int i = 128; i < 196; i++) {
+ Character ch = CharUtils.toCharacterObject((char) i);
+ Character ch2 = CharUtils.toCharacterObject((char) i);
+ assertEquals(ch, ch2);
+ assertTrue(ch != ch2);
+ assertEquals(i, ch.charValue());
+ assertEquals(i, ch2.charValue());
+ }
+ }
+
+ @Test
+ public void testToCharacterObject_String() {
+ assertEquals(null, CharUtils.toCharacterObject(null));
+ assertEquals(null, CharUtils.toCharacterObject(""));
+ assertEquals(new Character('a'), CharUtils.toCharacterObject("a"));
+ assertEquals(new Character('a'), CharUtils.toCharacterObject("abc"));
+ assertSame(CharUtils.toCharacterObject("a"), CharUtils.toCharacterObject("a"));
+ assertSame(CharUtils.toCharacterObject("a"), CharUtils.toCharacterObject('a'));
+ }
+
+ @Test
+ public void testToChar_Character() {
+ assertEquals('A', CharUtils.toChar(CHARACTER_A));
+ assertEquals('B', CharUtils.toChar(CHARACTER_B));
+ try {
+ CharUtils.toChar((Character) null);
+ } catch (IllegalArgumentException ex) {}
+ }
+
+ @Test
+ public void testToChar_Character_char() {
+ assertEquals('A', CharUtils.toChar(CHARACTER_A, 'X'));
+ assertEquals('B', CharUtils.toChar(CHARACTER_B, 'X'));
+ assertEquals('X', CharUtils.toChar((Character) null, 'X'));
+ }
+
+ @Test
+ public void testToChar_String() {
+ assertEquals('A', CharUtils.toChar("A"));
+ assertEquals('B', CharUtils.toChar("BA"));
+ try {
+ CharUtils.toChar((String) null);
+ } catch (IllegalArgumentException ex) {}
+ try {
+ CharUtils.toChar("");
+ } catch (IllegalArgumentException ex) {}
+ }
+
+ @Test
+ public void testToChar_String_char() {
+ assertEquals('A', CharUtils.toChar("A", 'X'));
+ assertEquals('B', CharUtils.toChar("BA", 'X'));
+ assertEquals('X', CharUtils.toChar("", 'X'));
+ assertEquals('X', CharUtils.toChar((String) null, 'X'));
+ }
+
+ @Test
+ public void testToIntValue_char() {
+ assertEquals(0, CharUtils.toIntValue('0'));
+ assertEquals(1, CharUtils.toIntValue('1'));
+ assertEquals(2, CharUtils.toIntValue('2'));
+ assertEquals(3, CharUtils.toIntValue('3'));
+ assertEquals(4, CharUtils.toIntValue('4'));
+ assertEquals(5, CharUtils.toIntValue('5'));
+ assertEquals(6, CharUtils.toIntValue('6'));
+ assertEquals(7, CharUtils.toIntValue('7'));
+ assertEquals(8, CharUtils.toIntValue('8'));
+ assertEquals(9, CharUtils.toIntValue('9'));
+ try {
+ CharUtils.toIntValue('a');
+ } catch (IllegalArgumentException ex) {}
+ }
+
+ @Test
+ public void testToIntValue_char_int() {
+ assertEquals(0, CharUtils.toIntValue('0', -1));
+ assertEquals(3, CharUtils.toIntValue('3', -1));
+ assertEquals(-1, CharUtils.toIntValue('a', -1));
+ }
+
+ @Test
+ public void testToIntValue_Character() {
+ assertEquals(0, CharUtils.toIntValue(new Character('0')));
+ assertEquals(3, CharUtils.toIntValue(new Character('3')));
+ try {
+ CharUtils.toIntValue(null);
+ } catch (IllegalArgumentException ex) {}
+ try {
+ CharUtils.toIntValue(CHARACTER_A);
+ } catch (IllegalArgumentException ex) {}
+ }
+
+ @Test
+ public void testToIntValue_Character_int() {
+ assertEquals(0, CharUtils.toIntValue(new Character('0'), -1));
+ assertEquals(3, CharUtils.toIntValue(new Character('3'), -1));
+ assertEquals(-1, CharUtils.toIntValue(new Character('A'), -1));
+ assertEquals(-1, CharUtils.toIntValue(null, -1));
+ }
+
+ @Test
+ public void testToString_char() {
+ assertEquals("a", CharUtils.toString('a'));
+ assertSame(CharUtils.toString('a'), CharUtils.toString('a'));
+
+ for (int i = 0; i < 128; i++) {
+ String str = CharUtils.toString((char) i);
+ String str2 = CharUtils.toString((char) i);
+ assertSame(str, str2);
+ assertEquals(1, str.length());
+ assertEquals(i, str.charAt(0));
+ }
+ for (int i = 128; i < 196; i++) {
+ String str = CharUtils.toString((char) i);
+ String str2 = CharUtils.toString((char) i);
+ assertEquals(str, str2);
+ assertTrue(str != str2);
+ assertEquals(1, str.length());
+ assertEquals(i, str.charAt(0));
+ assertEquals(1, str2.length());
+ assertEquals(i, str2.charAt(0));
+ }
+ }
+
+ @Test
+ public void testToString_Character() {
+ assertEquals(null, CharUtils.toString(null));
+ assertEquals("A", CharUtils.toString(CHARACTER_A));
+ assertSame(CharUtils.toString(CHARACTER_A), CharUtils.toString(CHARACTER_A));
+ }
+
+ @Test
+ public void testToUnicodeEscaped_char() {
+ assertEquals("\\u0041", CharUtils.unicodeEscaped('A'));
+
+ for (int i = 0; i < 196; i++) {
+ String str = CharUtils.unicodeEscaped((char) i);
+ assertEquals(6, str.length());
+ int val = Integer.parseInt(str.substring(2), 16);
+ assertEquals(i, val);
+ }
+ assertEquals("\\u0999", CharUtils.unicodeEscaped((char) 0x999));
+ assertEquals("\\u1001", CharUtils.unicodeEscaped((char) 0x1001));
+ }
+
+ @Test
+ public void testToUnicodeEscaped_Character() {
+ assertEquals(null, CharUtils.unicodeEscaped(null));
+ assertEquals("\\u0041", CharUtils.unicodeEscaped(CHARACTER_A));
+ }
+
+ @Test
+ public void testIsAscii_char() {
+ assertTrue(CharUtils.isAscii('a'));
+ assertTrue(CharUtils.isAscii('A'));
+ assertTrue(CharUtils.isAscii('3'));
+ assertTrue(CharUtils.isAscii('-'));
+ assertTrue(CharUtils.isAscii('\n'));
+ assertFalse(CharUtils.isAscii(CHAR_COPY));
+
+ for (int i = 0; i < 128; i++) {
+ if (i < 128) {
+ assertTrue(CharUtils.isAscii((char) i));
+ } else {
+ assertFalse(CharUtils.isAscii((char) i));
+ }
+ }
+ }
+
+ @Test
+ public void testIsAsciiPrintable_char() {
+ assertTrue(CharUtils.isAsciiPrintable('a'));
+ assertTrue(CharUtils.isAsciiPrintable('A'));
+ assertTrue(CharUtils.isAsciiPrintable('3'));
+ assertTrue(CharUtils.isAsciiPrintable('-'));
+ assertFalse(CharUtils.isAsciiPrintable('\n'));
+ assertFalse(CharUtils.isAscii(CHAR_COPY));
+
+ for (int i = 0; i < 196; i++) {
+ if (i >= 32 && i <= 126) {
+ assertTrue(CharUtils.isAsciiPrintable((char) i));
+ } else {
+ assertFalse(CharUtils.isAsciiPrintable((char) i));
+ }
+ }
+ }
+
+ @Test
+ public void testIsAsciiControl_char() {
+ assertFalse(CharUtils.isAsciiControl('a'));
+ assertFalse(CharUtils.isAsciiControl('A'));
+ assertFalse(CharUtils.isAsciiControl('3'));
+ assertFalse(CharUtils.isAsciiControl('-'));
+ assertTrue(CharUtils.isAsciiControl('\n'));
+ assertFalse(CharUtils.isAsciiControl(CHAR_COPY));
+
+ for (int i = 0; i < 196; i++) {
+ if (i < 32 || i == 127) {
+ assertTrue(CharUtils.isAsciiControl((char) i));
+ } else {
+ assertFalse(CharUtils.isAsciiControl((char) i));
+ }
+ }
+ }
+
+ @Test
+ public void testIsAsciiAlpha_char() {
+ assertTrue(CharUtils.isAsciiAlpha('a'));
+ assertTrue(CharUtils.isAsciiAlpha('A'));
+ assertFalse(CharUtils.isAsciiAlpha('3'));
+ assertFalse(CharUtils.isAsciiAlpha('-'));
+ assertFalse(CharUtils.isAsciiAlpha('\n'));
+ assertFalse(CharUtils.isAsciiAlpha(CHAR_COPY));
+
+ for (int i = 0; i < 196; i++) {
+ if ((i >= 'A' && i <= 'Z') || (i >= 'a' && i <= 'z')) {
+ assertTrue(CharUtils.isAsciiAlpha((char) i));
+ } else {
+ assertFalse(CharUtils.isAsciiAlpha((char) i));
+ }
+ }
+ }
+
+ @Test
+ public void testIsAsciiAlphaUpper_char() {
+ assertFalse(CharUtils.isAsciiAlphaUpper('a'));
+ assertTrue(CharUtils.isAsciiAlphaUpper('A'));
+ assertFalse(CharUtils.isAsciiAlphaUpper('3'));
+ assertFalse(CharUtils.isAsciiAlphaUpper('-'));
+ assertFalse(CharUtils.isAsciiAlphaUpper('\n'));
+ assertFalse(CharUtils.isAsciiAlphaUpper(CHAR_COPY));
+
+ for (int i = 0; i < 196; i++) {
+ if (i >= 'A' && i <= 'Z') {
+ assertTrue(CharUtils.isAsciiAlphaUpper((char) i));
+ } else {
+ assertFalse(CharUtils.isAsciiAlphaUpper((char) i));
+ }
+ }
+ }
+
+ @Test
+ public void testIsAsciiAlphaLower_char() {
+ assertTrue(CharUtils.isAsciiAlphaLower('a'));
+ assertFalse(CharUtils.isAsciiAlphaLower('A'));
+ assertFalse(CharUtils.isAsciiAlphaLower('3'));
+ assertFalse(CharUtils.isAsciiAlphaLower('-'));
+ assertFalse(CharUtils.isAsciiAlphaLower('\n'));
+ assertFalse(CharUtils.isAsciiAlphaLower(CHAR_COPY));
+
+ for (int i = 0; i < 196; i++) {
+ if (i >= 'a' && i <= 'z') {
+ assertTrue(CharUtils.isAsciiAlphaLower((char) i));
+ } else {
+ assertFalse(CharUtils.isAsciiAlphaLower((char) i));
+ }
+ }
+ }
+
+ @Test
+ public void testIsAsciiNumeric_char() {
+ assertFalse(CharUtils.isAsciiNumeric('a'));
+ assertFalse(CharUtils.isAsciiNumeric('A'));
+ assertTrue(CharUtils.isAsciiNumeric('3'));
+ assertFalse(CharUtils.isAsciiNumeric('-'));
+ assertFalse(CharUtils.isAsciiNumeric('\n'));
+ assertFalse(CharUtils.isAsciiNumeric(CHAR_COPY));
+
+ for (int i = 0; i < 196; i++) {
+ if (i >= '0' && i <= '9') {
+ assertTrue(CharUtils.isAsciiNumeric((char) i));
+ } else {
+ assertFalse(CharUtils.isAsciiNumeric((char) i));
+ }
+ }
+ }
+
+ @Test
+ public void testIsAsciiAlphanumeric_char() {
+ assertTrue(CharUtils.isAsciiAlphanumeric('a'));
+ assertTrue(CharUtils.isAsciiAlphanumeric('A'));
+ assertTrue(CharUtils.isAsciiAlphanumeric('3'));
+ assertFalse(CharUtils.isAsciiAlphanumeric('-'));
+ assertFalse(CharUtils.isAsciiAlphanumeric('\n'));
+ assertFalse(CharUtils.isAsciiAlphanumeric(CHAR_COPY));
+
+ for (int i = 0; i < 196; i++) {
+ if ((i >= 'A' && i <= 'Z') || (i >= 'a' && i <= 'z') || (i >= '0' && i <= '9')) {
+ assertTrue(CharUtils.isAsciiAlphanumeric((char) i));
+ } else {
+ assertFalse(CharUtils.isAsciiAlphanumeric((char) i));
+ }
+ }
+ }
+
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/ClassUtils.java b/ApacheCommonsLang/org/apache/commons/lang3/ClassUtils.java
new file mode 100644
index 0000000..184344c
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/ClassUtils.java
@@ -0,0 +1,1132 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+package org.apache.commons.lang3;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+
+
+/**
+ * Operates on classes without using reflection.
+ *
+ * This class handles invalid {@code null} inputs as best it can.
+ * Each method documents its behaviour in more detail.
+ *
+ * The notion of a {@code canonical name} includes the human
+ * readable name for the type, for example {@code int[]}. The
+ * non-canonical method variants work with the JVM names, such as
+ * {@code [I}.
+ *
+ * @since 2.0
+ * @version $Id: ClassUtils.java 1299411 2012-03-11 17:55:29Z ggregory $
+ */
+public class ClassUtils {
+
+ /**
+ * The package separator character: '.' == {@value}
.
+ */
+ public static final char PACKAGE_SEPARATOR_CHAR = '.';
+
+ /**
+ * The package separator String: "."
.
+ */
+ public static final String PACKAGE_SEPARATOR = String.valueOf(PACKAGE_SEPARATOR_CHAR);
+
+ /**
+ * The inner class separator character: '$' == {@value}
.
+ */
+ public static final char INNER_CLASS_SEPARATOR_CHAR = '$';
+
+ /**
+ * The inner class separator String: {@code "$"}.
+ */
+ public static final String INNER_CLASS_SEPARATOR = String.valueOf(INNER_CLASS_SEPARATOR_CHAR);
+
+ /**
+ * Maps primitive {@code Class}es to their corresponding wrapper {@code Class}.
+ */
+ private static final Map, Class>> primitiveWrapperMap = new HashMap, Class>>();
+ static {
+ primitiveWrapperMap.put(Boolean.TYPE, Boolean.class);
+ primitiveWrapperMap.put(Byte.TYPE, Byte.class);
+ primitiveWrapperMap.put(Character.TYPE, Character.class);
+ primitiveWrapperMap.put(Short.TYPE, Short.class);
+ primitiveWrapperMap.put(Integer.TYPE, Integer.class);
+ primitiveWrapperMap.put(Long.TYPE, Long.class);
+ primitiveWrapperMap.put(Double.TYPE, Double.class);
+ primitiveWrapperMap.put(Float.TYPE, Float.class);
+ primitiveWrapperMap.put(Void.TYPE, Void.TYPE);
+ }
+
+ /**
+ * Maps wrapper {@code Class}es to their corresponding primitive types.
+ */
+ private static final Map, Class>> wrapperPrimitiveMap = new HashMap, Class>>();
+ static {
+ for (Class> primitiveClass : primitiveWrapperMap.keySet()) {
+ Class> wrapperClass = primitiveWrapperMap.get(primitiveClass);
+ if (!primitiveClass.equals(wrapperClass)) {
+ wrapperPrimitiveMap.put(wrapperClass, primitiveClass);
+ }
+ }
+ }
+
+ /**
+ * Maps a primitive class name to its corresponding abbreviation used in array class names.
+ */
+ private static final Map abbreviationMap = new HashMap();
+
+ /**
+ * Maps an abbreviation used in array class names to corresponding primitive class name.
+ */
+ private static final Map reverseAbbreviationMap = new HashMap();
+
+ /**
+ * Add primitive type abbreviation to maps of abbreviations.
+ *
+ * @param primitive Canonical name of primitive type
+ * @param abbreviation Corresponding abbreviation of primitive type
+ */
+ private static void addAbbreviation(String primitive, String abbreviation) {
+ abbreviationMap.put(primitive, abbreviation);
+ reverseAbbreviationMap.put(abbreviation, primitive);
+ }
+
+ /**
+ * Feed abbreviation maps
+ */
+ static {
+ addAbbreviation("int", "I");
+ addAbbreviation("boolean", "Z");
+ addAbbreviation("float", "F");
+ addAbbreviation("long", "J");
+ addAbbreviation("short", "S");
+ addAbbreviation("byte", "B");
+ addAbbreviation("double", "D");
+ addAbbreviation("char", "C");
+ }
+
+ /**
+ * ClassUtils instances should NOT be constructed in standard programming.
+ * Instead, the class should be used as
+ * {@code ClassUtils.getShortClassName(cls)}.
+ *
+ * This constructor is public to permit tools that require a JavaBean
+ * instance to operate.
+ */
+ public ClassUtils() {
+ super();
+ }
+
+ // Short class name
+ // ----------------------------------------------------------------------
+ /**
+ * Gets the class name minus the package name for an {@code Object}.
+ *
+ * @param object the class to get the short name for, may be null
+ * @param valueIfNull the value to return if null
+ * @return the class name of the object without the package name, or the null value
+ */
+ public static String getShortClassName(Object object, String valueIfNull) {
+ if (object == null) {
+ return valueIfNull;
+ }
+ return getShortClassName(object.getClass());
+ }
+
+ /**
+ * Gets the class name minus the package name from a {@code Class}.
+ *
+ * Consider using the Java 5 API {@link Class#getSimpleName()} instead.
+ * The one known difference is that this code will return {@code "Map.Entry"} while
+ * the {@code java.lang.Class} variant will simply return {@code "Entry"}.
+ *
+ * @param cls the class to get the short name for.
+ * @return the class name without the package name or an empty string
+ */
+ public static String getShortClassName(Class> cls) {
+ if (cls == null) {
+ return StringUtils.EMPTY;
+ }
+ return getShortClassName(cls.getName());
+ }
+
+ /**
+ * Gets the class name minus the package name from a String.
+ *
+ * The string passed in is assumed to be a class name - it is not checked.
+
+ * Note that this method differs from Class.getSimpleName() in that this will
+ * return {@code "Map.Entry"} whilst the {@code java.lang.Class} variant will simply
+ * return {@code "Entry"}.
+ *
+ * @param className the className to get the short name for
+ * @return the class name of the class without the package name or an empty string
+ */
+ public static String getShortClassName(String className) {
+ if (StringUtils.isEmpty(className)) {
+ return StringUtils.EMPTY;
+ }
+
+ StringBuilder arrayPrefix = new StringBuilder();
+
+ // Handle array encoding
+ if (className.startsWith("[")) {
+ while (className.charAt(0) == '[') {
+ className = className.substring(1);
+ arrayPrefix.append("[]");
+ }
+ // Strip Object type encoding
+ if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') {
+ className = className.substring(1, className.length() - 1);
+ }
+ }
+
+ if (reverseAbbreviationMap.containsKey(className)) {
+ className = reverseAbbreviationMap.get(className);
+ }
+
+ int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
+ int innerIdx = className.indexOf(
+ INNER_CLASS_SEPARATOR_CHAR, lastDotIdx == -1 ? 0 : lastDotIdx + 1);
+ String out = className.substring(lastDotIdx + 1);
+ if (innerIdx != -1) {
+ out = out.replace(INNER_CLASS_SEPARATOR_CHAR, PACKAGE_SEPARATOR_CHAR);
+ }
+ return out + arrayPrefix;
+ }
+
+ /**
+ * Null-safe version of aClass.getSimpleName()
+ *
+ * @param cls the class for which to get the simple name.
+ * @return the simple class name.
+ * @since 3.0
+ * @see Class#getSimpleName()
+ */
+ public static String getSimpleName(Class> cls) {
+ if (cls == null) {
+ return StringUtils.EMPTY;
+ }
+ return cls.getSimpleName();
+ }
+
+ /**
+ * Null-safe version of aClass.getSimpleName()
+ *
+ * @param object the object for which to get the simple class name.
+ * @param valueIfNull the value to return if object
is null
+ * @return the simple class name.
+ * @since 3.0
+ * @see Class#getSimpleName()
+ */
+ public static String getSimpleName(Object object, String valueIfNull) {
+ if (object == null) {
+ return valueIfNull;
+ }
+ return getSimpleName(object.getClass());
+ }
+
+ // Package name
+ // ----------------------------------------------------------------------
+ /**
+ * Gets the package name of an {@code Object}.
+ *
+ * @param object the class to get the package name for, may be null
+ * @param valueIfNull the value to return if null
+ * @return the package name of the object, or the null value
+ */
+ public static String getPackageName(Object object, String valueIfNull) {
+ if (object == null) {
+ return valueIfNull;
+ }
+ return getPackageName(object.getClass());
+ }
+
+ /**
+ * Gets the package name of a {@code Class}.
+ *
+ * @param cls the class to get the package name for, may be {@code null}.
+ * @return the package name or an empty string
+ */
+ public static String getPackageName(Class> cls) {
+ if (cls == null) {
+ return StringUtils.EMPTY;
+ }
+ return getPackageName(cls.getName());
+ }
+
+ /**
+ * Gets the package name from a {@code String}.
+ *
+ * The string passed in is assumed to be a class name - it is not checked.
+ * If the class is unpackaged, return an empty string.
+ *
+ * @param className the className to get the package name for, may be {@code null}
+ * @return the package name or an empty string
+ */
+ public static String getPackageName(String className) {
+ if (StringUtils.isEmpty(className)) {
+ return StringUtils.EMPTY;
+ }
+
+ // Strip array encoding
+ while (className.charAt(0) == '[') {
+ className = className.substring(1);
+ }
+ // Strip Object type encoding
+ if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') {
+ className = className.substring(1);
+ }
+
+ int i = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
+ if (i == -1) {
+ return StringUtils.EMPTY;
+ }
+ return className.substring(0, i);
+ }
+
+ // Superclasses/Superinterfaces
+ // ----------------------------------------------------------------------
+ /**
+ * Gets a {@code List} of superclasses for the given class.
+ *
+ * @param cls the class to look up, may be {@code null}
+ * @return the {@code List} of superclasses in order going up from this one
+ * {@code null} if null input
+ */
+ public static List> getAllSuperclasses(Class> cls) {
+ if (cls == null) {
+ return null;
+ }
+ List> classes = new ArrayList>();
+ Class> superclass = cls.getSuperclass();
+ while (superclass != null) {
+ classes.add(superclass);
+ superclass = superclass.getSuperclass();
+ }
+ return classes;
+ }
+
+ /**
+ * Gets a {@code List} of all interfaces implemented by the given
+ * class and its superclasses.
+ *
+ * The order is determined by looking through each interface in turn as
+ * declared in the source file and following its hierarchy up. Then each
+ * superclass is considered in the same way. Later duplicates are ignored,
+ * so the order is maintained.
+ *
+ * @param cls the class to look up, may be {@code null}
+ * @return the {@code List} of interfaces in order,
+ * {@code null} if null input
+ */
+ public static List> getAllInterfaces(Class> cls) {
+ if (cls == null) {
+ return null;
+ }
+
+ LinkedHashSet> interfacesFound = new LinkedHashSet>();
+ getAllInterfaces(cls, interfacesFound);
+
+ return new ArrayList>(interfacesFound);
+ }
+
+ /**
+ * Get the interfaces for the specified class.
+ *
+ * @param cls the class to look up, may be {@code null}
+ * @param interfacesFound the {@code Set} of interfaces for the class
+ */
+ private static void getAllInterfaces(Class> cls, HashSet> interfacesFound) {
+ while (cls != null) {
+ Class>[] interfaces = cls.getInterfaces();
+
+ for (Class> i : interfaces) {
+ if (interfacesFound.add(i)) {
+ getAllInterfaces(i, interfacesFound);
+ }
+ }
+
+ cls = cls.getSuperclass();
+ }
+ }
+
+ // Convert list
+ // ----------------------------------------------------------------------
+ /**
+ * Given a {@code List} of class names, this method converts them into classes.
+ *
+ * A new {@code List} is returned. If the class name cannot be found, {@code null}
+ * is stored in the {@code List}. If the class name in the {@code List} is
+ * {@code null}, {@code null} is stored in the output {@code List}.
+ *
+ * @param classNames the classNames to change
+ * @return a {@code List} of Class objects corresponding to the class names,
+ * {@code null} if null input
+ * @throws ClassCastException if classNames contains a non String entry
+ */
+ public static List> convertClassNamesToClasses(List classNames) {
+ if (classNames == null) {
+ return null;
+ }
+ List> classes = new ArrayList>(classNames.size());
+ for (String className : classNames) {
+ try {
+ classes.add(Class.forName(className));
+ } catch (Exception ex) {
+ classes.add(null);
+ }
+ }
+ return classes;
+ }
+
+ /**
+ * Given a {@code List} of {@code Class} objects, this method converts
+ * them into class names.
+ *
+ * A new {@code List} is returned. {@code null} objects will be copied into
+ * the returned list as {@code null}.
+ *
+ * @param classes the classes to change
+ * @return a {@code List} of class names corresponding to the Class objects,
+ * {@code null} if null input
+ * @throws ClassCastException if {@code classes} contains a non-{@code Class} entry
+ */
+ public static List convertClassesToClassNames(List> classes) {
+ if (classes == null) {
+ return null;
+ }
+ List classNames = new ArrayList(classes.size());
+ for (Class> cls : classes) {
+ if (cls == null) {
+ classNames.add(null);
+ } else {
+ classNames.add(cls.getName());
+ }
+ }
+ return classNames;
+ }
+
+ // Is assignable
+ // ----------------------------------------------------------------------
+ /**
+ * Checks if an array of Classes can be assigned to another array of Classes.
+ *
+ * This method calls {@link #isAssignable(Class, Class) isAssignable} for each
+ * Class pair in the input arrays. It can be used to check if a set of arguments
+ * (the first parameter) are suitably compatible with a set of method parameter types
+ * (the second parameter).
+ *
+ * Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, this
+ * method takes into account widenings of primitive classes and
+ * {@code null}s.
+ *
+ * Primitive widenings allow an int to be assigned to a {@code long},
+ * {@code float} or {@code double}. This method returns the correct
+ * result for these cases.
+ *
+ * {@code Null} may be assigned to any reference type. This method will
+ * return {@code true} if {@code null} is passed in and the toClass is
+ * non-primitive.
+ *
+ * Specifically, this method tests whether the type represented by the
+ * specified {@code Class} parameter can be converted to the type
+ * represented by this {@code Class} object via an identity conversion
+ * widening primitive or widening reference conversion. See
+ * The Java Language Specification ,
+ * sections 5.1.1, 5.1.2 and 5.1.4 for details.
+ *
+ * Since Lang 3.0, this method will default behavior for
+ * calculating assignability between primitive and wrapper types corresponding
+ * to the running Java version ; i.e. autoboxing will be the default
+ * behavior in VMs running Java versions >= 1.5.
+ *
+ * @param classArray the array of Classes to check, may be {@code null}
+ * @param toClassArray the array of Classes to try to assign into, may be {@code null}
+ * @return {@code true} if assignment possible
+ */
+ public static boolean isAssignable(Class>[] classArray, Class>... toClassArray) {
+ return isAssignable(classArray, toClassArray, SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_5));
+ }
+
+ /**
+ * Checks if an array of Classes can be assigned to another array of Classes.
+ *
+ * This method calls {@link #isAssignable(Class, Class) isAssignable} for each
+ * Class pair in the input arrays. It can be used to check if a set of arguments
+ * (the first parameter) are suitably compatible with a set of method parameter types
+ * (the second parameter).
+ *
+ * Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, this
+ * method takes into account widenings of primitive classes and
+ * {@code null}s.
+ *
+ * Primitive widenings allow an int to be assigned to a {@code long},
+ * {@code float} or {@code double}. This method returns the correct
+ * result for these cases.
+ *
+ * {@code Null} may be assigned to any reference type. This method will
+ * return {@code true} if {@code null} is passed in and the toClass is
+ * non-primitive.
+ *
+ * Specifically, this method tests whether the type represented by the
+ * specified {@code Class} parameter can be converted to the type
+ * represented by this {@code Class} object via an identity conversion
+ * widening primitive or widening reference conversion. See
+ * The Java Language Specification ,
+ * sections 5.1.1, 5.1.2 and 5.1.4 for details.
+ *
+ * @param classArray the array of Classes to check, may be {@code null}
+ * @param toClassArray the array of Classes to try to assign into, may be {@code null}
+ * @param autoboxing whether to use implicit autoboxing/unboxing between primitives and wrappers
+ * @return {@code true} if assignment possible
+ */
+ public static boolean isAssignable(Class>[] classArray, Class>[] toClassArray, boolean autoboxing) {
+ if (ArrayUtils.isSameLength(classArray, toClassArray) == false) {
+ return false;
+ }
+ if (classArray == null) {
+ classArray = ArrayUtils.EMPTY_CLASS_ARRAY;
+ }
+ if (toClassArray == null) {
+ toClassArray = ArrayUtils.EMPTY_CLASS_ARRAY;
+ }
+ for (int i = 0; i < classArray.length; i++) {
+ if (isAssignable(classArray[i], toClassArray[i], autoboxing) == false) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Returns whether the given {@code type} is a primitive or primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character},
+ * {@link Short}, {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
+ *
+ * @param type
+ * The class to query or null.
+ * @return true if the given {@code type} is a primitive or primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character},
+ * {@link Short}, {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
+ * @since 3.1
+ */
+ public static boolean isPrimitiveOrWrapper(Class> type) {
+ if (type == null) {
+ return false;
+ }
+ return type.isPrimitive() || isPrimitiveWrapper(type);
+ }
+
+ /**
+ * Returns whether the given {@code type} is a primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character}, {@link Short},
+ * {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
+ *
+ * @param type
+ * The class to query or null.
+ * @return true if the given {@code type} is a primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character}, {@link Short},
+ * {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
+ * @since 3.1
+ */
+ public static boolean isPrimitiveWrapper(Class> type) {
+ return wrapperPrimitiveMap.containsKey(type);
+ }
+
+ /**
+ * Checks if one {@code Class} can be assigned to a variable of
+ * another {@code Class}.
+ *
+ * Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method,
+ * this method takes into account widenings of primitive classes and
+ * {@code null}s.
+ *
+ * Primitive widenings allow an int to be assigned to a long, float or
+ * double. This method returns the correct result for these cases.
+ *
+ * {@code Null} may be assigned to any reference type. This method
+ * will return {@code true} if {@code null} is passed in and the
+ * toClass is non-primitive.
+ *
+ * Specifically, this method tests whether the type represented by the
+ * specified {@code Class} parameter can be converted to the type
+ * represented by this {@code Class} object via an identity conversion
+ * widening primitive or widening reference conversion. See
+ * The Java Language Specification ,
+ * sections 5.1.1, 5.1.2 and 5.1.4 for details.
+ *
+ * Since Lang 3.0, this method will default behavior for
+ * calculating assignability between primitive and wrapper types corresponding
+ * to the running Java version ; i.e. autoboxing will be the default
+ * behavior in VMs running Java versions >= 1.5.
+ *
+ * @param cls the Class to check, may be null
+ * @param toClass the Class to try to assign into, returns false if null
+ * @return {@code true} if assignment possible
+ */
+ public static boolean isAssignable(Class> cls, Class> toClass) {
+ return isAssignable(cls, toClass, SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_5));
+ }
+
+ /**
+ * Checks if one {@code Class} can be assigned to a variable of
+ * another {@code Class}.
+ *
+ * Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method,
+ * this method takes into account widenings of primitive classes and
+ * {@code null}s.
+ *
+ * Primitive widenings allow an int to be assigned to a long, float or
+ * double. This method returns the correct result for these cases.
+ *
+ * {@code Null} may be assigned to any reference type. This method
+ * will return {@code true} if {@code null} is passed in and the
+ * toClass is non-primitive.
+ *
+ * Specifically, this method tests whether the type represented by the
+ * specified {@code Class} parameter can be converted to the type
+ * represented by this {@code Class} object via an identity conversion
+ * widening primitive or widening reference conversion. See
+ * The Java Language Specification ,
+ * sections 5.1.1, 5.1.2 and 5.1.4 for details.
+ *
+ * @param cls the Class to check, may be null
+ * @param toClass the Class to try to assign into, returns false if null
+ * @param autoboxing whether to use implicit autoboxing/unboxing between primitives and wrappers
+ * @return {@code true} if assignment possible
+ */
+ public static boolean isAssignable(Class> cls, Class> toClass, boolean autoboxing) {
+ if (toClass == null) {
+ return false;
+ }
+ // have to check for null, as isAssignableFrom doesn't
+ if (cls == null) {
+ return !toClass.isPrimitive();
+ }
+ //autoboxing:
+ if (autoboxing) {
+ if (cls.isPrimitive() && !toClass.isPrimitive()) {
+ cls = primitiveToWrapper(cls);
+ if (cls == null) {
+ return false;
+ }
+ }
+ if (toClass.isPrimitive() && !cls.isPrimitive()) {
+ cls = wrapperToPrimitive(cls);
+ if (cls == null) {
+ return false;
+ }
+ }
+ }
+ if (cls.equals(toClass)) {
+ return true;
+ }
+ if (cls.isPrimitive()) {
+ if (toClass.isPrimitive() == false) {
+ return false;
+ }
+ if (Integer.TYPE.equals(cls)) {
+ return Long.TYPE.equals(toClass)
+ || Float.TYPE.equals(toClass)
+ || Double.TYPE.equals(toClass);
+ }
+ if (Long.TYPE.equals(cls)) {
+ return Float.TYPE.equals(toClass)
+ || Double.TYPE.equals(toClass);
+ }
+ if (Boolean.TYPE.equals(cls)) {
+ return false;
+ }
+ if (Double.TYPE.equals(cls)) {
+ return false;
+ }
+ if (Float.TYPE.equals(cls)) {
+ return Double.TYPE.equals(toClass);
+ }
+ if (Character.TYPE.equals(cls)) {
+ return Integer.TYPE.equals(toClass)
+ || Long.TYPE.equals(toClass)
+ || Float.TYPE.equals(toClass)
+ || Double.TYPE.equals(toClass);
+ }
+ if (Short.TYPE.equals(cls)) {
+ return Integer.TYPE.equals(toClass)
+ || Long.TYPE.equals(toClass)
+ || Float.TYPE.equals(toClass)
+ || Double.TYPE.equals(toClass);
+ }
+ if (Byte.TYPE.equals(cls)) {
+ return Short.TYPE.equals(toClass)
+ || Integer.TYPE.equals(toClass)
+ || Long.TYPE.equals(toClass)
+ || Float.TYPE.equals(toClass)
+ || Double.TYPE.equals(toClass);
+ }
+ // should never get here
+ return false;
+ }
+ return toClass.isAssignableFrom(cls);
+ }
+
+ /**
+ * Converts the specified primitive Class object to its corresponding
+ * wrapper Class object.
+ *
+ * NOTE: From v2.2, this method handles {@code Void.TYPE},
+ * returning {@code Void.TYPE}.
+ *
+ * @param cls the class to convert, may be null
+ * @return the wrapper class for {@code cls} or {@code cls} if
+ * {@code cls} is not a primitive. {@code null} if null input.
+ * @since 2.1
+ */
+ public static Class> primitiveToWrapper(Class> cls) {
+ Class> convertedClass = cls;
+ if (cls != null && cls.isPrimitive()) {
+ convertedClass = primitiveWrapperMap.get(cls);
+ }
+ return convertedClass;
+ }
+
+ /**
+ * Converts the specified array of primitive Class objects to an array of
+ * its corresponding wrapper Class objects.
+ *
+ * @param classes the class array to convert, may be null or empty
+ * @return an array which contains for each given class, the wrapper class or
+ * the original class if class is not a primitive. {@code null} if null input.
+ * Empty array if an empty array passed in.
+ * @since 2.1
+ */
+ public static Class>[] primitivesToWrappers(Class>... classes) {
+ if (classes == null) {
+ return null;
+ }
+
+ if (classes.length == 0) {
+ return classes;
+ }
+
+ Class>[] convertedClasses = new Class[classes.length];
+ for (int i = 0; i < classes.length; i++) {
+ convertedClasses[i] = primitiveToWrapper(classes[i]);
+ }
+ return convertedClasses;
+ }
+
+ /**
+ * Converts the specified wrapper class to its corresponding primitive
+ * class.
+ *
+ * This method is the counter part of {@code primitiveToWrapper()}.
+ * If the passed in class is a wrapper class for a primitive type, this
+ * primitive type will be returned (e.g. {@code Integer.TYPE} for
+ * {@code Integer.class}). For other classes, or if the parameter is
+ * null , the return value is null .
+ *
+ * @param cls the class to convert, may be null
+ * @return the corresponding primitive type if {@code cls} is a
+ * wrapper class, null otherwise
+ * @see #primitiveToWrapper(Class)
+ * @since 2.4
+ */
+ public static Class> wrapperToPrimitive(Class> cls) {
+ return wrapperPrimitiveMap.get(cls);
+ }
+
+ /**
+ * Converts the specified array of wrapper Class objects to an array of
+ * its corresponding primitive Class objects.
+ *
+ * This method invokes {@code wrapperToPrimitive()} for each element
+ * of the passed in array.
+ *
+ * @param classes the class array to convert, may be null or empty
+ * @return an array which contains for each given class, the primitive class or
+ * null if the original class is not a wrapper class. {@code null} if null input.
+ * Empty array if an empty array passed in.
+ * @see #wrapperToPrimitive(Class)
+ * @since 2.4
+ */
+ public static Class>[] wrappersToPrimitives(Class>... classes) {
+ if (classes == null) {
+ return null;
+ }
+
+ if (classes.length == 0) {
+ return classes;
+ }
+
+ Class>[] convertedClasses = new Class[classes.length];
+ for (int i = 0; i < classes.length; i++) {
+ convertedClasses[i] = wrapperToPrimitive(classes[i]);
+ }
+ return convertedClasses;
+ }
+
+ // Inner class
+ // ----------------------------------------------------------------------
+ /**
+ * Is the specified class an inner class or static nested class.
+ *
+ * @param cls the class to check, may be null
+ * @return {@code true} if the class is an inner or static nested class,
+ * false if not or {@code null}
+ */
+ public static boolean isInnerClass(Class> cls) {
+ return cls != null && cls.getEnclosingClass() != null;
+ }
+
+ // Class loading
+ // ----------------------------------------------------------------------
+ /**
+ * Returns the class represented by {@code className} using the
+ * {@code classLoader}. This implementation supports the syntaxes
+ * "{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}",
+ * "{@code [Ljava.util.Map.Entry;}", and "{@code [Ljava.util.Map$Entry;}".
+ *
+ * @param classLoader the class loader to use to load the class
+ * @param className the class name
+ * @param initialize whether the class must be initialized
+ * @return the class represented by {@code className} using the {@code classLoader}
+ * @throws ClassNotFoundException if the class is not found
+ */
+ public static Class> getClass(
+ ClassLoader classLoader, String className, boolean initialize) throws ClassNotFoundException {
+ try {
+ Class> clazz;
+ if (abbreviationMap.containsKey(className)) {
+ String clsName = "[" + abbreviationMap.get(className);
+ clazz = Class.forName(clsName, initialize, classLoader).getComponentType();
+ } else {
+ clazz = Class.forName(toCanonicalName(className), initialize, classLoader);
+ }
+ return clazz;
+ } catch (ClassNotFoundException ex) {
+ // allow path separators (.) as inner class name separators
+ int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
+
+ if (lastDotIndex != -1) {
+ try {
+ return getClass(classLoader, className.substring(0, lastDotIndex) +
+ INNER_CLASS_SEPARATOR_CHAR + className.substring(lastDotIndex + 1),
+ initialize);
+ } catch (ClassNotFoundException ex2) { // NOPMD
+ // ignore exception
+ }
+ }
+
+ throw ex;
+ }
+ }
+
+ /**
+ * Returns the (initialized) class represented by {@code className}
+ * using the {@code classLoader}. This implementation supports
+ * the syntaxes "{@code java.util.Map.Entry[]}",
+ * "{@code java.util.Map$Entry[]}", "{@code [Ljava.util.Map.Entry;}",
+ * and "{@code [Ljava.util.Map$Entry;}".
+ *
+ * @param classLoader the class loader to use to load the class
+ * @param className the class name
+ * @return the class represented by {@code className} using the {@code classLoader}
+ * @throws ClassNotFoundException if the class is not found
+ */
+ public static Class> getClass(ClassLoader classLoader, String className) throws ClassNotFoundException {
+ return getClass(classLoader, className, true);
+ }
+
+ /**
+ * Returns the (initialized) class represented by {@code className}
+ * using the current thread's context class loader. This implementation
+ * supports the syntaxes "{@code java.util.Map.Entry[]}",
+ * "{@code java.util.Map$Entry[]}", "{@code [Ljava.util.Map.Entry;}",
+ * and "{@code [Ljava.util.Map$Entry;}".
+ *
+ * @param className the class name
+ * @return the class represented by {@code className} using the current thread's context class loader
+ * @throws ClassNotFoundException if the class is not found
+ */
+ public static Class> getClass(String className) throws ClassNotFoundException {
+ return getClass(className, true);
+ }
+
+ /**
+ * Returns the class represented by {@code className} using the
+ * current thread's context class loader. This implementation supports the
+ * syntaxes "{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}",
+ * "{@code [Ljava.util.Map.Entry;}", and "{@code [Ljava.util.Map$Entry;}".
+ *
+ * @param className the class name
+ * @param initialize whether the class must be initialized
+ * @return the class represented by {@code className} using the current thread's context class loader
+ * @throws ClassNotFoundException if the class is not found
+ */
+ public static Class> getClass(String className, boolean initialize) throws ClassNotFoundException {
+ ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
+ ClassLoader loader = contextCL == null ? ClassUtils.class.getClassLoader() : contextCL;
+ return getClass(loader, className, initialize);
+ }
+
+ // Public method
+ // ----------------------------------------------------------------------
+ /**
+ * Returns the desired Method much like {@code Class.getMethod}, however
+ * it ensures that the returned Method is from a public class or interface and not
+ * from an anonymous inner class. This means that the Method is invokable and
+ * doesn't fall foul of Java bug
+ * 4071957 ).
+ *
+ * Set set = Collections.unmodifiableSet(...);
+ * Method method = ClassUtils.getPublicMethod(set.getClass(), "isEmpty", new Class[0]);
+ * Object result = method.invoke(set, new Object[]);
+ *
+ *
+ * @param cls the class to check, not null
+ * @param methodName the name of the method
+ * @param parameterTypes the list of parameters
+ * @return the method
+ * @throws NullPointerException if the class is null
+ * @throws SecurityException if a a security violation occured
+ * @throws NoSuchMethodException if the method is not found in the given class
+ * or if the metothod doen't conform with the requirements
+ */
+ public static Method getPublicMethod(Class> cls, String methodName, Class>... parameterTypes)
+ throws SecurityException, NoSuchMethodException {
+
+ Method declaredMethod = cls.getMethod(methodName, parameterTypes);
+ if (Modifier.isPublic(declaredMethod.getDeclaringClass().getModifiers())) {
+ return declaredMethod;
+ }
+
+ List> candidateClasses = new ArrayList>();
+ candidateClasses.addAll(getAllInterfaces(cls));
+ candidateClasses.addAll(getAllSuperclasses(cls));
+
+ for (Class> candidateClass : candidateClasses) {
+ if (!Modifier.isPublic(candidateClass.getModifiers())) {
+ continue;
+ }
+ Method candidateMethod;
+ try {
+ candidateMethod = candidateClass.getMethod(methodName, parameterTypes);
+ } catch (NoSuchMethodException ex) {
+ continue;
+ }
+ if (Modifier.isPublic(candidateMethod.getDeclaringClass().getModifiers())) {
+ return candidateMethod;
+ }
+ }
+
+ throw new NoSuchMethodException("Can't find a public method for " +
+ methodName + " " + ArrayUtils.toString(parameterTypes));
+ }
+
+ // ----------------------------------------------------------------------
+ /**
+ * Converts a class name to a JLS style class name.
+ *
+ * @param className the class name
+ * @return the converted name
+ */
+ private static String toCanonicalName(String className) {
+ className = StringUtils.deleteWhitespace(className);
+ if (className == null) {
+ throw new NullPointerException("className must not be null.");
+ } else if (className.endsWith("[]")) {
+ StringBuilder classNameBuffer = new StringBuilder();
+ while (className.endsWith("[]")) {
+ className = className.substring(0, className.length() - 2);
+ classNameBuffer.append("[");
+ }
+ String abbreviation = abbreviationMap.get(className);
+ if (abbreviation != null) {
+ classNameBuffer.append(abbreviation);
+ } else {
+ classNameBuffer.append("L").append(className).append(";");
+ }
+ className = classNameBuffer.toString();
+ }
+ return className;
+ }
+
+ /**
+ * Converts an array of {@code Object} in to an array of {@code Class} objects.
+ * If any of these objects is null, a null element will be inserted into the array.
+ *
+ * This method returns {@code null} for a {@code null} input array.
+ *
+ * @param array an {@code Object} array
+ * @return a {@code Class} array, {@code null} if null array input
+ * @since 2.4
+ */
+ public static Class>[] toClass(Object... array) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return ArrayUtils.EMPTY_CLASS_ARRAY;
+ }
+ Class>[] classes = new Class[array.length];
+ for (int i = 0; i < array.length; i++) {
+ classes[i] = array[i] == null ? null : array[i].getClass();
+ }
+ return classes;
+ }
+
+ // Short canonical name
+ // ----------------------------------------------------------------------
+ /**
+ * Gets the canonical name minus the package name for an {@code Object}.
+ *
+ * @param object the class to get the short name for, may be null
+ * @param valueIfNull the value to return if null
+ * @return the canonical name of the object without the package name, or the null value
+ * @since 2.4
+ */
+ public static String getShortCanonicalName(Object object, String valueIfNull) {
+ if (object == null) {
+ return valueIfNull;
+ }
+ return getShortCanonicalName(object.getClass().getName());
+ }
+
+ /**
+ * Gets the canonical name minus the package name from a {@code Class}.
+ *
+ * @param cls the class to get the short name for.
+ * @return the canonical name without the package name or an empty string
+ * @since 2.4
+ */
+ public static String getShortCanonicalName(Class> cls) {
+ if (cls == null) {
+ return StringUtils.EMPTY;
+ }
+ return getShortCanonicalName(cls.getName());
+ }
+
+ /**
+ * Gets the canonical name minus the package name from a String.
+ *
+ * The string passed in is assumed to be a canonical name - it is not checked.
+ *
+ * @param canonicalName the class name to get the short name for
+ * @return the canonical name of the class without the package name or an empty string
+ * @since 2.4
+ */
+ public static String getShortCanonicalName(String canonicalName) {
+ return ClassUtils.getShortClassName(getCanonicalName(canonicalName));
+ }
+
+ // Package name
+ // ----------------------------------------------------------------------
+ /**
+ * Gets the package name from the canonical name of an {@code Object}.
+ *
+ * @param object the class to get the package name for, may be null
+ * @param valueIfNull the value to return if null
+ * @return the package name of the object, or the null value
+ * @since 2.4
+ */
+ public static String getPackageCanonicalName(Object object, String valueIfNull) {
+ if (object == null) {
+ return valueIfNull;
+ }
+ return getPackageCanonicalName(object.getClass().getName());
+ }
+
+ /**
+ * Gets the package name from the canonical name of a {@code Class}.
+ *
+ * @param cls the class to get the package name for, may be {@code null}.
+ * @return the package name or an empty string
+ * @since 2.4
+ */
+ public static String getPackageCanonicalName(Class> cls) {
+ if (cls == null) {
+ return StringUtils.EMPTY;
+ }
+ return getPackageCanonicalName(cls.getName());
+ }
+
+ /**
+ * Gets the package name from the canonical name.
+ *
+ * The string passed in is assumed to be a canonical name - it is not checked.
+ * If the class is unpackaged, return an empty string.
+ *
+ * @param canonicalName the canonical name to get the package name for, may be {@code null}
+ * @return the package name or an empty string
+ * @since 2.4
+ */
+ public static String getPackageCanonicalName(String canonicalName) {
+ return ClassUtils.getPackageName(getCanonicalName(canonicalName));
+ }
+
+ /**
+ * Converts a given name of class into canonical format.
+ * If name of class is not a name of array class it returns
+ * unchanged name.
+ * Example:
+ *
+ * {@code getCanonicalName("[I") = "int[]"}
+ * {@code getCanonicalName("[Ljava.lang.String;") = "java.lang.String[]"}
+ * {@code getCanonicalName("java.lang.String") = "java.lang.String"}
+ *
+ *
+ *
+ * @param className the name of class
+ * @return canonical form of class name
+ * @since 2.4
+ */
+ private static String getCanonicalName(String className) {
+ className = StringUtils.deleteWhitespace(className);
+ if (className == null) {
+ return null;
+ } else {
+ int dim = 0;
+ while (className.startsWith("[")) {
+ dim++;
+ className = className.substring(1);
+ }
+ if (dim < 1) {
+ return className;
+ } else {
+ if (className.startsWith("L")) {
+ className = className.substring(
+ 1,
+ className.endsWith(";")
+ ? className.length() - 1
+ : className.length());
+ } else {
+ if (className.length() > 0) {
+ className = reverseAbbreviationMap.get(className.substring(0, 1));
+ }
+ }
+ StringBuilder canonicalClassNameBuffer = new StringBuilder(className);
+ for (int i = 0; i < dim; i++) {
+ canonicalClassNameBuffer.append("[]");
+ }
+ return canonicalClassNameBuffer.toString();
+ }
+ }
+ }
+
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/ClassUtilsTest.java b/ApacheCommonsLang/org/apache/commons/lang3/ClassUtilsTest.java
new file mode 100644
index 0000000..b7716ea
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/ClassUtilsTest.java
@@ -0,0 +1,1165 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+package org.apache.commons.lang3;
+
+import static org.apache.commons.lang3.JavaVersion.JAVA_1_5;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import junit.framework.TestCase;
+
+/**
+ * Unit tests {@link org.apache.commons.lang3.ClassUtils}.
+ *
+ * @version $Id: ClassUtilsTest.java 1199730 2011-11-09 13:00:47Z sebb $
+ */
+public class ClassUtilsTest extends TestCase {
+
+ public ClassUtilsTest(String name) {
+ super(name);
+ }
+
+ private static class Inner {
+ private class DeeplyNested{}
+ }
+
+ //-----------------------------------------------------------------------
+ public void testConstructor() {
+ assertNotNull(new ClassUtils());
+ Constructor>[] cons = ClassUtils.class.getDeclaredConstructors();
+ assertEquals(1, cons.length);
+ assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
+ assertEquals(true, Modifier.isPublic(ClassUtils.class.getModifiers()));
+ assertEquals(false, Modifier.isFinal(ClassUtils.class.getModifiers()));
+ }
+
+ // -------------------------------------------------------------------------
+ public void test_getShortClassName_Object() {
+ assertEquals("ClassUtils", ClassUtils.getShortClassName(new ClassUtils(), ""));
+ assertEquals("ClassUtilsTest.Inner", ClassUtils.getShortClassName(new Inner(), ""));
+ assertEquals("String", ClassUtils.getShortClassName("hello", ""));
+ assertEquals("", ClassUtils.getShortClassName(null, ""));
+
+ // Inner types
+ class Named extends Object {}
+ assertEquals("ClassUtilsTest.1", ClassUtils.getShortClassName(new Object(){}, ""));
+ assertEquals("ClassUtilsTest.1Named", ClassUtils.getShortClassName(new Named(), ""));
+ assertEquals("ClassUtilsTest.Inner", ClassUtils.getShortClassName(new Inner(), ""));
+ }
+
+ public void test_getShortClassName_Class() {
+ assertEquals("ClassUtils", ClassUtils.getShortClassName(ClassUtils.class));
+ assertEquals("Map.Entry", ClassUtils.getShortClassName(Map.Entry.class));
+ assertEquals("", ClassUtils.getShortClassName((Class>) null));
+
+ // LANG-535
+ assertEquals("String[]", ClassUtils.getShortClassName(String[].class));
+ assertEquals("Map.Entry[]", ClassUtils.getShortClassName(Map.Entry[].class));
+
+ // Primitives
+ assertEquals("boolean", ClassUtils.getShortClassName(boolean.class));
+ assertEquals("byte", ClassUtils.getShortClassName(byte.class));
+ assertEquals("char", ClassUtils.getShortClassName(char.class));
+ assertEquals("short", ClassUtils.getShortClassName(short.class));
+ assertEquals("int", ClassUtils.getShortClassName(int.class));
+ assertEquals("long", ClassUtils.getShortClassName(long.class));
+ assertEquals("float", ClassUtils.getShortClassName(float.class));
+ assertEquals("double", ClassUtils.getShortClassName(double.class));
+
+ // Primitive Arrays
+ assertEquals("boolean[]", ClassUtils.getShortClassName(boolean[].class));
+ assertEquals("byte[]", ClassUtils.getShortClassName(byte[].class));
+ assertEquals("char[]", ClassUtils.getShortClassName(char[].class));
+ assertEquals("short[]", ClassUtils.getShortClassName(short[].class));
+ assertEquals("int[]", ClassUtils.getShortClassName(int[].class));
+ assertEquals("long[]", ClassUtils.getShortClassName(long[].class));
+ assertEquals("float[]", ClassUtils.getShortClassName(float[].class));
+ assertEquals("double[]", ClassUtils.getShortClassName(double[].class));
+
+ // Arrays of arrays of ...
+ assertEquals("String[][]", ClassUtils.getShortClassName(String[][].class));
+ assertEquals("String[][][]", ClassUtils.getShortClassName(String[][][].class));
+ assertEquals("String[][][][]", ClassUtils.getShortClassName(String[][][][].class));
+
+ // Inner types
+ class Named extends Object {}
+ assertEquals("ClassUtilsTest.2", ClassUtils.getShortClassName(new Object(){}.getClass()));
+ assertEquals("ClassUtilsTest.2Named", ClassUtils.getShortClassName(Named.class));
+ assertEquals("ClassUtilsTest.Inner", ClassUtils.getShortClassName(Inner.class));
+ }
+
+
+
+ public void test_getShortClassName_String() {
+ assertEquals("ClassUtils", ClassUtils.getShortClassName(ClassUtils.class.getName()));
+ assertEquals("Map.Entry", ClassUtils.getShortClassName(Map.Entry.class.getName()));
+ assertEquals("", ClassUtils.getShortClassName((String) null));
+ assertEquals("", ClassUtils.getShortClassName(""));
+ }
+
+ public void test_getSimpleName_Class() {
+ assertEquals("ClassUtils", ClassUtils.getSimpleName(ClassUtils.class));
+ assertEquals("Entry", ClassUtils.getSimpleName(Map.Entry.class));
+ assertEquals("", ClassUtils.getSimpleName((Class>) null));
+
+ // LANG-535
+ assertEquals("String[]", ClassUtils.getSimpleName(String[].class));
+ assertEquals("Entry[]", ClassUtils.getSimpleName(Map.Entry[].class));
+
+ // Primitives
+ assertEquals("boolean", ClassUtils.getSimpleName(boolean.class));
+ assertEquals("byte", ClassUtils.getSimpleName(byte.class));
+ assertEquals("char", ClassUtils.getSimpleName(char.class));
+ assertEquals("short", ClassUtils.getSimpleName(short.class));
+ assertEquals("int", ClassUtils.getSimpleName(int.class));
+ assertEquals("long", ClassUtils.getSimpleName(long.class));
+ assertEquals("float", ClassUtils.getSimpleName(float.class));
+ assertEquals("double", ClassUtils.getSimpleName(double.class));
+
+ // Primitive Arrays
+ assertEquals("boolean[]", ClassUtils.getSimpleName(boolean[].class));
+ assertEquals("byte[]", ClassUtils.getSimpleName(byte[].class));
+ assertEquals("char[]", ClassUtils.getSimpleName(char[].class));
+ assertEquals("short[]", ClassUtils.getSimpleName(short[].class));
+ assertEquals("int[]", ClassUtils.getSimpleName(int[].class));
+ assertEquals("long[]", ClassUtils.getSimpleName(long[].class));
+ assertEquals("float[]", ClassUtils.getSimpleName(float[].class));
+ assertEquals("double[]", ClassUtils.getSimpleName(double[].class));
+
+ // Arrays of arrays of ...
+ assertEquals("String[][]", ClassUtils.getSimpleName(String[][].class));
+ assertEquals("String[][][]", ClassUtils.getSimpleName(String[][][].class));
+ assertEquals("String[][][][]", ClassUtils.getSimpleName(String[][][][].class));
+
+ // On-the-fly types
+ class Named extends Object {}
+ assertEquals("", ClassUtils.getSimpleName(new Object(){}.getClass()));
+ assertEquals("Named", ClassUtils.getSimpleName(Named.class));
+ }
+
+ public void test_getSimpleName_Object() {
+ assertEquals("ClassUtils", ClassUtils.getSimpleName(new ClassUtils(), ""));
+ assertEquals("Inner", ClassUtils.getSimpleName(new Inner(), ""));
+ assertEquals("String", ClassUtils.getSimpleName("hello", ""));
+ assertEquals("", ClassUtils.getSimpleName(null, ""));
+ }
+
+ // -------------------------------------------------------------------------
+ public void test_getPackageName_Object() {
+ assertEquals("org.apache.commons.lang3", ClassUtils.getPackageName(new ClassUtils(), ""));
+ assertEquals("org.apache.commons.lang3", ClassUtils.getPackageName(new Inner(), ""));
+ assertEquals("", ClassUtils.getPackageName(null, ""));
+ }
+
+ public void test_getPackageName_Class() {
+ assertEquals("java.lang", ClassUtils.getPackageName(String.class));
+ assertEquals("java.util", ClassUtils.getPackageName(Map.Entry.class));
+ assertEquals("", ClassUtils.getPackageName((Class>)null));
+
+ // LANG-535
+ assertEquals("java.lang", ClassUtils.getPackageName(String[].class));
+
+ // Primitive Arrays
+ assertEquals("", ClassUtils.getPackageName(boolean[].class));
+ assertEquals("", ClassUtils.getPackageName(byte[].class));
+ assertEquals("", ClassUtils.getPackageName(char[].class));
+ assertEquals("", ClassUtils.getPackageName(short[].class));
+ assertEquals("", ClassUtils.getPackageName(int[].class));
+ assertEquals("", ClassUtils.getPackageName(long[].class));
+ assertEquals("", ClassUtils.getPackageName(float[].class));
+ assertEquals("", ClassUtils.getPackageName(double[].class));
+
+ // Arrays of arrays of ...
+ assertEquals("java.lang", ClassUtils.getPackageName(String[][].class));
+ assertEquals("java.lang", ClassUtils.getPackageName(String[][][].class));
+ assertEquals("java.lang", ClassUtils.getPackageName(String[][][][].class));
+
+ // On-the-fly types
+ class Named extends Object {}
+ assertEquals("org.apache.commons.lang3", ClassUtils.getPackageName(new Object(){}.getClass()));
+ assertEquals("org.apache.commons.lang3", ClassUtils.getPackageName(Named.class));
+ }
+
+ public void test_getPackageName_String() {
+ assertEquals("org.apache.commons.lang3", ClassUtils.getPackageName(ClassUtils.class.getName()));
+ assertEquals("java.util", ClassUtils.getPackageName(Map.Entry.class.getName()));
+ assertEquals("", ClassUtils.getPackageName((String)null));
+ assertEquals("", ClassUtils.getPackageName(""));
+ }
+
+ // -------------------------------------------------------------------------
+ public void test_getAllSuperclasses_Class() {
+ List> list = ClassUtils.getAllSuperclasses(CY.class);
+ assertEquals(2, list.size());
+ assertEquals(CX.class, list.get(0));
+ assertEquals(Object.class, list.get(1));
+
+ assertEquals(null, ClassUtils.getAllSuperclasses(null));
+ }
+
+ public void test_getAllInterfaces_Class() {
+ List> list = ClassUtils.getAllInterfaces(CY.class);
+ assertEquals(6, list.size());
+ assertEquals(IB.class, list.get(0));
+ assertEquals(IC.class, list.get(1));
+ assertEquals(ID.class, list.get(2));
+ assertEquals(IE.class, list.get(3));
+ assertEquals(IF.class, list.get(4));
+ assertEquals(IA.class, list.get(5));
+
+ assertEquals(null, ClassUtils.getAllInterfaces(null));
+ }
+
+ private static interface IA {
+ }
+ private static interface IB {
+ }
+ private static interface IC extends ID, IE {
+ }
+ private static interface ID {
+ }
+ private static interface IE extends IF {
+ }
+ private static interface IF {
+ }
+ private static class CX implements IB, IA, IE {
+ }
+ private static class CY extends CX implements IB, IC {
+ }
+
+ // -------------------------------------------------------------------------
+ public void test_convertClassNamesToClasses_List() {
+ List list = new ArrayList();
+ List> result = ClassUtils.convertClassNamesToClasses(list);
+ assertEquals(0, result.size());
+
+ list.add("java.lang.String");
+ list.add("java.lang.xxx");
+ list.add("java.lang.Object");
+ result = ClassUtils.convertClassNamesToClasses(list);
+ assertEquals(3, result.size());
+ assertEquals(String.class, result.get(0));
+ assertEquals(null, result.get(1));
+ assertEquals(Object.class, result.get(2));
+
+ @SuppressWarnings("unchecked") // test what happens when non-generic code adds wrong type of element
+ List olist = (List)(List>)list;
+ olist.add(new Object());
+ try {
+ ClassUtils.convertClassNamesToClasses(list);
+ fail("Should not have been able to convert list");
+ } catch (ClassCastException expected) {}
+ assertEquals(null, ClassUtils.convertClassNamesToClasses(null));
+ }
+
+ public void test_convertClassesToClassNames_List() {
+ List> list = new ArrayList>();
+ List result = ClassUtils.convertClassesToClassNames(list);
+ assertEquals(0, result.size());
+
+ list.add(String.class);
+ list.add(null);
+ list.add(Object.class);
+ result = ClassUtils.convertClassesToClassNames(list);
+ assertEquals(3, result.size());
+ assertEquals("java.lang.String", result.get(0));
+ assertEquals(null, result.get(1));
+ assertEquals("java.lang.Object", result.get(2));
+
+ @SuppressWarnings("unchecked") // test what happens when non-generic code adds wrong type of element
+ List olist = (List)(List>)list;
+ olist.add(new Object());
+ try {
+ ClassUtils.convertClassesToClassNames(list);
+ fail("Should not have been able to convert list");
+ } catch (ClassCastException expected) {}
+ assertEquals(null, ClassUtils.convertClassesToClassNames(null));
+ }
+
+ // -------------------------------------------------------------------------
+ public void test_isInnerClass_Class() {
+ assertEquals(true, ClassUtils.isInnerClass(Inner.class));
+ assertEquals(true, ClassUtils.isInnerClass(Map.Entry.class));
+ assertEquals(true, ClassUtils.isInnerClass(new Cloneable() {
+ }.getClass()));
+ assertEquals(false, ClassUtils.isInnerClass(this.getClass()));
+ assertEquals(false, ClassUtils.isInnerClass(String.class));
+ assertEquals(false, ClassUtils.isInnerClass(null));
+ }
+
+ // -------------------------------------------------------------------------
+ public void test_isAssignable_ClassArray_ClassArray() throws Exception {
+ Class>[] array2 = new Class[] {Object.class, Object.class};
+ Class>[] array1 = new Class[] {Object.class};
+ Class>[] array1s = new Class[] {String.class};
+ Class>[] array0 = new Class[] {};
+ Class>[] arrayPrimitives = { Integer.TYPE, Boolean.TYPE };
+ Class>[] arrayWrappers = { Integer.class, Boolean.class };
+
+ assertFalse(ClassUtils.isAssignable(array1, array2));
+ assertFalse(ClassUtils.isAssignable(null, array2));
+ assertTrue(ClassUtils.isAssignable(null, array0));
+ assertTrue(ClassUtils.isAssignable(array0, array0));
+// assertTrue(ClassUtils.isAssignable(array0, null));
+ assertTrue(ClassUtils.isAssignable(array0, (Class>[]) null)); // explicit cast to avoid warning
+ assertTrue(ClassUtils.isAssignable((Class[]) null, (Class[]) null));
+
+ assertFalse(ClassUtils.isAssignable(array1, array1s));
+ assertTrue(ClassUtils.isAssignable(array1s, array1s));
+ assertTrue(ClassUtils.isAssignable(array1s, array1));
+
+ boolean autoboxing = SystemUtils.isJavaVersionAtLeast(JAVA_1_5);
+
+ assertEquals(autoboxing, ClassUtils.isAssignable(arrayPrimitives, arrayWrappers));
+ assertEquals(autoboxing, ClassUtils.isAssignable(arrayWrappers, arrayPrimitives));
+ assertFalse(ClassUtils.isAssignable(arrayPrimitives, array1));
+ assertFalse(ClassUtils.isAssignable(arrayWrappers, array1));
+ assertEquals(autoboxing, ClassUtils.isAssignable(arrayPrimitives, array2));
+ assertTrue(ClassUtils.isAssignable(arrayWrappers, array2));
+ }
+
+ public void test_isAssignable_ClassArray_ClassArray_Autoboxing() throws Exception {
+ Class>[] array2 = new Class[] {Object.class, Object.class};
+ Class>[] array1 = new Class[] {Object.class};
+ Class>[] array1s = new Class[] {String.class};
+ Class>[] array0 = new Class[] {};
+ Class>[] arrayPrimitives = { Integer.TYPE, Boolean.TYPE };
+ Class>[] arrayWrappers = { Integer.class, Boolean.class };
+
+ assertFalse(ClassUtils.isAssignable(array1, array2, true));
+ assertFalse(ClassUtils.isAssignable(null, array2, true));
+ assertTrue(ClassUtils.isAssignable(null, array0, true));
+ assertTrue(ClassUtils.isAssignable(array0, array0, true));
+ assertTrue(ClassUtils.isAssignable(array0, null, true));
+ assertTrue(ClassUtils.isAssignable((Class[]) null, (Class[]) null, true));
+
+ assertFalse(ClassUtils.isAssignable(array1, array1s, true));
+ assertTrue(ClassUtils.isAssignable(array1s, array1s, true));
+ assertTrue(ClassUtils.isAssignable(array1s, array1, true));
+
+ assertTrue(ClassUtils.isAssignable(arrayPrimitives, arrayWrappers, true));
+ assertTrue(ClassUtils.isAssignable(arrayWrappers, arrayPrimitives, true));
+ assertFalse(ClassUtils.isAssignable(arrayPrimitives, array1, true));
+ assertFalse(ClassUtils.isAssignable(arrayWrappers, array1, true));
+ assertTrue(ClassUtils.isAssignable(arrayPrimitives, array2, true));
+ assertTrue(ClassUtils.isAssignable(arrayWrappers, array2, true));
+ }
+
+ public void test_isAssignable_ClassArray_ClassArray_NoAutoboxing() throws Exception {
+ Class>[] array2 = new Class[] {Object.class, Object.class};
+ Class>[] array1 = new Class[] {Object.class};
+ Class>[] array1s = new Class[] {String.class};
+ Class>[] array0 = new Class[] {};
+ Class>[] arrayPrimitives = { Integer.TYPE, Boolean.TYPE };
+ Class>[] arrayWrappers = { Integer.class, Boolean.class };
+
+ assertFalse(ClassUtils.isAssignable(array1, array2, false));
+ assertFalse(ClassUtils.isAssignable(null, array2, false));
+ assertTrue(ClassUtils.isAssignable(null, array0, false));
+ assertTrue(ClassUtils.isAssignable(array0, array0, false));
+ assertTrue(ClassUtils.isAssignable(array0, null, false));
+ assertTrue(ClassUtils.isAssignable((Class[]) null, (Class[]) null, false));
+
+ assertFalse(ClassUtils.isAssignable(array1, array1s, false));
+ assertTrue(ClassUtils.isAssignable(array1s, array1s, false));
+ assertTrue(ClassUtils.isAssignable(array1s, array1, false));
+
+ assertFalse(ClassUtils.isAssignable(arrayPrimitives, arrayWrappers, false));
+ assertFalse(ClassUtils.isAssignable(arrayWrappers, arrayPrimitives, false));
+ assertFalse(ClassUtils.isAssignable(arrayPrimitives, array1, false));
+ assertFalse(ClassUtils.isAssignable(arrayWrappers, array1, false));
+ assertTrue(ClassUtils.isAssignable(arrayWrappers, array2, false));
+ assertFalse(ClassUtils.isAssignable(arrayPrimitives, array2, false));
+ }
+
+ public void test_isAssignable() throws Exception {
+ assertFalse(ClassUtils.isAssignable((Class>) null, null));
+ assertFalse(ClassUtils.isAssignable(String.class, null));
+
+ assertTrue(ClassUtils.isAssignable(null, Object.class));
+ assertTrue(ClassUtils.isAssignable(null, Integer.class));
+ assertFalse(ClassUtils.isAssignable(null, Integer.TYPE));
+ assertTrue(ClassUtils.isAssignable(String.class, Object.class));
+ assertTrue(ClassUtils.isAssignable(String.class, String.class));
+ assertFalse(ClassUtils.isAssignable(Object.class, String.class));
+
+ boolean autoboxing = SystemUtils.isJavaVersionAtLeast(JAVA_1_5);
+
+ assertEquals(autoboxing, ClassUtils.isAssignable(Integer.TYPE, Integer.class));
+ assertEquals(autoboxing, ClassUtils.isAssignable(Integer.TYPE, Object.class));
+ assertEquals(autoboxing, ClassUtils.isAssignable(Integer.class, Integer.TYPE));
+ assertEquals(autoboxing, ClassUtils.isAssignable(Integer.class, Object.class));
+ assertTrue(ClassUtils.isAssignable(Integer.TYPE, Integer.TYPE));
+ assertTrue(ClassUtils.isAssignable(Integer.class, Integer.class));
+ assertEquals(autoboxing, ClassUtils.isAssignable(Boolean.TYPE, Boolean.class));
+ assertEquals(autoboxing, ClassUtils.isAssignable(Boolean.TYPE, Object.class));
+ assertEquals(autoboxing, ClassUtils.isAssignable(Boolean.class, Boolean.TYPE));
+ assertEquals(autoboxing, ClassUtils.isAssignable(Boolean.class, Object.class));
+ assertTrue(ClassUtils.isAssignable(Boolean.TYPE, Boolean.TYPE));
+ assertTrue(ClassUtils.isAssignable(Boolean.class, Boolean.class));
+ }
+
+ public void test_isAssignable_Autoboxing() throws Exception {
+ assertFalse(ClassUtils.isAssignable((Class>) null, null, true));
+ assertFalse(ClassUtils.isAssignable(String.class, null, true));
+
+ assertTrue(ClassUtils.isAssignable(null, Object.class, true));
+ assertTrue(ClassUtils.isAssignable(null, Integer.class, true));
+ assertFalse(ClassUtils.isAssignable(null, Integer.TYPE, true));
+ assertTrue(ClassUtils.isAssignable(String.class, Object.class, true));
+ assertTrue(ClassUtils.isAssignable(String.class, String.class, true));
+ assertFalse(ClassUtils.isAssignable(Object.class, String.class, true));
+ assertTrue(ClassUtils.isAssignable(Integer.TYPE, Integer.class, true));
+ assertTrue(ClassUtils.isAssignable(Integer.TYPE, Object.class, true));
+ assertTrue(ClassUtils.isAssignable(Integer.class, Integer.TYPE, true));
+ assertTrue(ClassUtils.isAssignable(Integer.class, Object.class, true));
+ assertTrue(ClassUtils.isAssignable(Integer.TYPE, Integer.TYPE, true));
+ assertTrue(ClassUtils.isAssignable(Integer.class, Integer.class, true));
+ assertTrue(ClassUtils.isAssignable(Boolean.TYPE, Boolean.class, true));
+ assertTrue(ClassUtils.isAssignable(Boolean.class, Boolean.TYPE, true));
+ assertTrue(ClassUtils.isAssignable(Boolean.class, Object.class, true));
+ assertTrue(ClassUtils.isAssignable(Boolean.TYPE, Boolean.TYPE, true));
+ assertTrue(ClassUtils.isAssignable(Boolean.class, Boolean.class, true));
+ }
+
+ public void test_isAssignable_NoAutoboxing() throws Exception {
+ assertFalse(ClassUtils.isAssignable((Class>) null, null, false));
+ assertFalse(ClassUtils.isAssignable(String.class, null, false));
+
+ assertTrue(ClassUtils.isAssignable(null, Object.class, false));
+ assertTrue(ClassUtils.isAssignable(null, Integer.class, false));
+ assertFalse(ClassUtils.isAssignable(null, Integer.TYPE, false));
+ assertTrue(ClassUtils.isAssignable(String.class, Object.class, false));
+ assertTrue(ClassUtils.isAssignable(String.class, String.class, false));
+ assertFalse(ClassUtils.isAssignable(Object.class, String.class, false));
+ assertFalse(ClassUtils.isAssignable(Integer.TYPE, Integer.class, false));
+ assertFalse(ClassUtils.isAssignable(Integer.TYPE, Object.class, false));
+ assertFalse(ClassUtils.isAssignable(Integer.class, Integer.TYPE, false));
+ assertTrue(ClassUtils.isAssignable(Integer.TYPE, Integer.TYPE, false));
+ assertTrue(ClassUtils.isAssignable(Integer.class, Integer.class, false));
+ assertFalse(ClassUtils.isAssignable(Boolean.TYPE, Boolean.class, false));
+ assertFalse(ClassUtils.isAssignable(Boolean.TYPE, Object.class, false));
+ assertFalse(ClassUtils.isAssignable(Boolean.class, Boolean.TYPE, false));
+ assertTrue(ClassUtils.isAssignable(Boolean.class, Object.class, false));
+ assertTrue(ClassUtils.isAssignable(Boolean.TYPE, Boolean.TYPE, false));
+ assertTrue(ClassUtils.isAssignable(Boolean.class, Boolean.class, false));
+ }
+
+ public void test_isAssignable_Widening() throws Exception {
+ // test byte conversions
+ assertFalse("byte -> char", ClassUtils.isAssignable(Byte.TYPE, Character.TYPE));
+ assertTrue("byte -> byte", ClassUtils.isAssignable(Byte.TYPE, Byte.TYPE));
+ assertTrue("byte -> short", ClassUtils.isAssignable(Byte.TYPE, Short.TYPE));
+ assertTrue("byte -> int", ClassUtils.isAssignable(Byte.TYPE, Integer.TYPE));
+ assertTrue("byte -> long", ClassUtils.isAssignable(Byte.TYPE, Long.TYPE));
+ assertTrue("byte -> float", ClassUtils.isAssignable(Byte.TYPE, Float.TYPE));
+ assertTrue("byte -> double", ClassUtils.isAssignable(Byte.TYPE, Double.TYPE));
+ assertFalse("byte -> boolean", ClassUtils.isAssignable(Byte.TYPE, Boolean.TYPE));
+
+ // test short conversions
+ assertFalse("short -> char", ClassUtils.isAssignable(Short.TYPE, Character.TYPE));
+ assertFalse("short -> byte", ClassUtils.isAssignable(Short.TYPE, Byte.TYPE));
+ assertTrue("short -> short", ClassUtils.isAssignable(Short.TYPE, Short.TYPE));
+ assertTrue("short -> int", ClassUtils.isAssignable(Short.TYPE, Integer.TYPE));
+ assertTrue("short -> long", ClassUtils.isAssignable(Short.TYPE, Long.TYPE));
+ assertTrue("short -> float", ClassUtils.isAssignable(Short.TYPE, Float.TYPE));
+ assertTrue("short -> double", ClassUtils.isAssignable(Short.TYPE, Double.TYPE));
+ assertFalse("short -> boolean", ClassUtils.isAssignable(Short.TYPE, Boolean.TYPE));
+
+ // test char conversions
+ assertTrue("char -> char", ClassUtils.isAssignable(Character.TYPE, Character.TYPE));
+ assertFalse("char -> byte", ClassUtils.isAssignable(Character.TYPE, Byte.TYPE));
+ assertFalse("char -> short", ClassUtils.isAssignable(Character.TYPE, Short.TYPE));
+ assertTrue("char -> int", ClassUtils.isAssignable(Character.TYPE, Integer.TYPE));
+ assertTrue("char -> long", ClassUtils.isAssignable(Character.TYPE, Long.TYPE));
+ assertTrue("char -> float", ClassUtils.isAssignable(Character.TYPE, Float.TYPE));
+ assertTrue("char -> double", ClassUtils.isAssignable(Character.TYPE, Double.TYPE));
+ assertFalse("char -> boolean", ClassUtils.isAssignable(Character.TYPE, Boolean.TYPE));
+
+ // test int conversions
+ assertFalse("int -> char", ClassUtils.isAssignable(Integer.TYPE, Character.TYPE));
+ assertFalse("int -> byte", ClassUtils.isAssignable(Integer.TYPE, Byte.TYPE));
+ assertFalse("int -> short", ClassUtils.isAssignable(Integer.TYPE, Short.TYPE));
+ assertTrue("int -> int", ClassUtils.isAssignable(Integer.TYPE, Integer.TYPE));
+ assertTrue("int -> long", ClassUtils.isAssignable(Integer.TYPE, Long.TYPE));
+ assertTrue("int -> float", ClassUtils.isAssignable(Integer.TYPE, Float.TYPE));
+ assertTrue("int -> double", ClassUtils.isAssignable(Integer.TYPE, Double.TYPE));
+ assertFalse("int -> boolean", ClassUtils.isAssignable(Integer.TYPE, Boolean.TYPE));
+
+ // test long conversions
+ assertFalse("long -> char", ClassUtils.isAssignable(Long.TYPE, Character.TYPE));
+ assertFalse("long -> byte", ClassUtils.isAssignable(Long.TYPE, Byte.TYPE));
+ assertFalse("long -> short", ClassUtils.isAssignable(Long.TYPE, Short.TYPE));
+ assertFalse("long -> int", ClassUtils.isAssignable(Long.TYPE, Integer.TYPE));
+ assertTrue("long -> long", ClassUtils.isAssignable(Long.TYPE, Long.TYPE));
+ assertTrue("long -> float", ClassUtils.isAssignable(Long.TYPE, Float.TYPE));
+ assertTrue("long -> double", ClassUtils.isAssignable(Long.TYPE, Double.TYPE));
+ assertFalse("long -> boolean", ClassUtils.isAssignable(Long.TYPE, Boolean.TYPE));
+
+ // test float conversions
+ assertFalse("float -> char", ClassUtils.isAssignable(Float.TYPE, Character.TYPE));
+ assertFalse("float -> byte", ClassUtils.isAssignable(Float.TYPE, Byte.TYPE));
+ assertFalse("float -> short", ClassUtils.isAssignable(Float.TYPE, Short.TYPE));
+ assertFalse("float -> int", ClassUtils.isAssignable(Float.TYPE, Integer.TYPE));
+ assertFalse("float -> long", ClassUtils.isAssignable(Float.TYPE, Long.TYPE));
+ assertTrue("float -> float", ClassUtils.isAssignable(Float.TYPE, Float.TYPE));
+ assertTrue("float -> double", ClassUtils.isAssignable(Float.TYPE, Double.TYPE));
+ assertFalse("float -> boolean", ClassUtils.isAssignable(Float.TYPE, Boolean.TYPE));
+
+ // test double conversions
+ assertFalse("double -> char", ClassUtils.isAssignable(Double.TYPE, Character.TYPE));
+ assertFalse("double -> byte", ClassUtils.isAssignable(Double.TYPE, Byte.TYPE));
+ assertFalse("double -> short", ClassUtils.isAssignable(Double.TYPE, Short.TYPE));
+ assertFalse("double -> int", ClassUtils.isAssignable(Double.TYPE, Integer.TYPE));
+ assertFalse("double -> long", ClassUtils.isAssignable(Double.TYPE, Long.TYPE));
+ assertFalse("double -> float", ClassUtils.isAssignable(Double.TYPE, Float.TYPE));
+ assertTrue("double -> double", ClassUtils.isAssignable(Double.TYPE, Double.TYPE));
+ assertFalse("double -> boolean", ClassUtils.isAssignable(Double.TYPE, Boolean.TYPE));
+
+ // test boolean conversions
+ assertFalse("boolean -> char", ClassUtils.isAssignable(Boolean.TYPE, Character.TYPE));
+ assertFalse("boolean -> byte", ClassUtils.isAssignable(Boolean.TYPE, Byte.TYPE));
+ assertFalse("boolean -> short", ClassUtils.isAssignable(Boolean.TYPE, Short.TYPE));
+ assertFalse("boolean -> int", ClassUtils.isAssignable(Boolean.TYPE, Integer.TYPE));
+ assertFalse("boolean -> long", ClassUtils.isAssignable(Boolean.TYPE, Long.TYPE));
+ assertFalse("boolean -> float", ClassUtils.isAssignable(Boolean.TYPE, Float.TYPE));
+ assertFalse("boolean -> double", ClassUtils.isAssignable(Boolean.TYPE, Double.TYPE));
+ assertTrue("boolean -> boolean", ClassUtils.isAssignable(Boolean.TYPE, Boolean.TYPE));
+ }
+
+ public void test_isAssignable_DefaultUnboxing_Widening() throws Exception {
+ boolean autoboxing = SystemUtils.isJavaVersionAtLeast(JAVA_1_5);
+
+ // test byte conversions
+ assertFalse("byte -> char", ClassUtils.isAssignable(Byte.class, Character.TYPE));
+ assertEquals("byte -> byte", autoboxing, ClassUtils.isAssignable(Byte.class, Byte.TYPE));
+ assertEquals("byte -> short", autoboxing, ClassUtils.isAssignable(Byte.class, Short.TYPE));
+ assertEquals("byte -> int", autoboxing, ClassUtils.isAssignable(Byte.class, Integer.TYPE));
+ assertEquals("byte -> long", autoboxing, ClassUtils.isAssignable(Byte.class, Long.TYPE));
+ assertEquals("byte -> float", autoboxing, ClassUtils.isAssignable(Byte.class, Float.TYPE));
+ assertEquals("byte -> double", autoboxing, ClassUtils.isAssignable(Byte.class, Double.TYPE));
+ assertFalse("byte -> boolean", ClassUtils.isAssignable(Byte.class, Boolean.TYPE));
+
+ // test short conversions
+ assertFalse("short -> char", ClassUtils.isAssignable(Short.class, Character.TYPE));
+ assertFalse("short -> byte", ClassUtils.isAssignable(Short.class, Byte.TYPE));
+ assertEquals("short -> short", autoboxing, ClassUtils.isAssignable(Short.class, Short.TYPE));
+ assertEquals("short -> int", autoboxing, ClassUtils.isAssignable(Short.class, Integer.TYPE));
+ assertEquals("short -> long", autoboxing, ClassUtils.isAssignable(Short.class, Long.TYPE));
+ assertEquals("short -> float", autoboxing, ClassUtils.isAssignable(Short.class, Float.TYPE));
+ assertEquals("short -> double", autoboxing, ClassUtils.isAssignable(Short.class, Double.TYPE));
+ assertFalse("short -> boolean", ClassUtils.isAssignable(Short.class, Boolean.TYPE));
+
+ // test char conversions
+ assertEquals("char -> char", autoboxing, ClassUtils.isAssignable(Character.class, Character.TYPE));
+ assertFalse("char -> byte", ClassUtils.isAssignable(Character.class, Byte.TYPE));
+ assertFalse("char -> short", ClassUtils.isAssignable(Character.class, Short.TYPE));
+ assertEquals("char -> int", autoboxing, ClassUtils.isAssignable(Character.class, Integer.TYPE));
+ assertEquals("char -> long", autoboxing, ClassUtils.isAssignable(Character.class, Long.TYPE));
+ assertEquals("char -> float", autoboxing, ClassUtils.isAssignable(Character.class, Float.TYPE));
+ assertEquals("char -> double", autoboxing, ClassUtils.isAssignable(Character.class, Double.TYPE));
+ assertFalse("char -> boolean", ClassUtils.isAssignable(Character.class, Boolean.TYPE));
+
+ // test int conversions
+ assertFalse("int -> char", ClassUtils.isAssignable(Integer.class, Character.TYPE));
+ assertFalse("int -> byte", ClassUtils.isAssignable(Integer.class, Byte.TYPE));
+ assertFalse("int -> short", ClassUtils.isAssignable(Integer.class, Short.TYPE));
+ assertEquals("int -> int", autoboxing, ClassUtils.isAssignable(Integer.class, Integer.TYPE));
+ assertEquals("int -> long", autoboxing, ClassUtils.isAssignable(Integer.class, Long.TYPE));
+ assertEquals("int -> float", autoboxing, ClassUtils.isAssignable(Integer.class, Float.TYPE));
+ assertEquals("int -> double", autoboxing, ClassUtils.isAssignable(Integer.class, Double.TYPE));
+ assertFalse("int -> boolean", ClassUtils.isAssignable(Integer.class, Boolean.TYPE));
+
+ // test long conversions
+ assertFalse("long -> char", ClassUtils.isAssignable(Long.class, Character.TYPE));
+ assertFalse("long -> byte", ClassUtils.isAssignable(Long.class, Byte.TYPE));
+ assertFalse("long -> short", ClassUtils.isAssignable(Long.class, Short.TYPE));
+ assertFalse("long -> int", ClassUtils.isAssignable(Long.class, Integer.TYPE));
+ assertEquals("long -> long", autoboxing, ClassUtils.isAssignable(Long.class, Long.TYPE));
+ assertEquals("long -> float", autoboxing, ClassUtils.isAssignable(Long.class, Float.TYPE));
+ assertEquals("long -> double", autoboxing, ClassUtils.isAssignable(Long.class, Double.TYPE));
+ assertFalse("long -> boolean", ClassUtils.isAssignable(Long.class, Boolean.TYPE));
+
+ // test float conversions
+ assertFalse("float -> char", ClassUtils.isAssignable(Float.class, Character.TYPE));
+ assertFalse("float -> byte", ClassUtils.isAssignable(Float.class, Byte.TYPE));
+ assertFalse("float -> short", ClassUtils.isAssignable(Float.class, Short.TYPE));
+ assertFalse("float -> int", ClassUtils.isAssignable(Float.class, Integer.TYPE));
+ assertFalse("float -> long", ClassUtils.isAssignable(Float.class, Long.TYPE));
+ assertEquals("float -> float", autoboxing, ClassUtils.isAssignable(Float.class, Float.TYPE));
+ assertEquals("float -> double", autoboxing, ClassUtils.isAssignable(Float.class, Double.TYPE));
+ assertFalse("float -> boolean", ClassUtils.isAssignable(Float.class, Boolean.TYPE));
+
+ // test double conversions
+ assertFalse("double -> char", ClassUtils.isAssignable(Double.class, Character.TYPE));
+ assertFalse("double -> byte", ClassUtils.isAssignable(Double.class, Byte.TYPE));
+ assertFalse("double -> short", ClassUtils.isAssignable(Double.class, Short.TYPE));
+ assertFalse("double -> int", ClassUtils.isAssignable(Double.class, Integer.TYPE));
+ assertFalse("double -> long", ClassUtils.isAssignable(Double.class, Long.TYPE));
+ assertFalse("double -> float", ClassUtils.isAssignable(Double.class, Float.TYPE));
+ assertEquals("double -> double", autoboxing, ClassUtils.isAssignable(Double.class, Double.TYPE));
+ assertFalse("double -> boolean", ClassUtils.isAssignable(Double.class, Boolean.TYPE));
+
+ // test boolean conversions
+ assertFalse("boolean -> char", ClassUtils.isAssignable(Boolean.class, Character.TYPE));
+ assertFalse("boolean -> byte", ClassUtils.isAssignable(Boolean.class, Byte.TYPE));
+ assertFalse("boolean -> short", ClassUtils.isAssignable(Boolean.class, Short.TYPE));
+ assertFalse("boolean -> int", ClassUtils.isAssignable(Boolean.class, Integer.TYPE));
+ assertFalse("boolean -> long", ClassUtils.isAssignable(Boolean.class, Long.TYPE));
+ assertFalse("boolean -> float", ClassUtils.isAssignable(Boolean.class, Float.TYPE));
+ assertFalse("boolean -> double", ClassUtils.isAssignable(Boolean.class, Double.TYPE));
+ assertEquals("boolean -> boolean", autoboxing, ClassUtils.isAssignable(Boolean.class, Boolean.TYPE));
+ }
+
+ public void test_isAssignable_Unboxing_Widening() throws Exception {
+ // test byte conversions
+ assertFalse("byte -> char", ClassUtils.isAssignable(Byte.class, Character.TYPE, true));
+ assertTrue("byte -> byte", ClassUtils.isAssignable(Byte.class, Byte.TYPE, true));
+ assertTrue("byte -> short", ClassUtils.isAssignable(Byte.class, Short.TYPE, true));
+ assertTrue("byte -> int", ClassUtils.isAssignable(Byte.class, Integer.TYPE, true));
+ assertTrue("byte -> long", ClassUtils.isAssignable(Byte.class, Long.TYPE, true));
+ assertTrue("byte -> float", ClassUtils.isAssignable(Byte.class, Float.TYPE, true));
+ assertTrue("byte -> double", ClassUtils.isAssignable(Byte.class, Double.TYPE, true));
+ assertFalse("byte -> boolean", ClassUtils.isAssignable(Byte.class, Boolean.TYPE, true));
+
+ // test short conversions
+ assertFalse("short -> char", ClassUtils.isAssignable(Short.class, Character.TYPE, true));
+ assertFalse("short -> byte", ClassUtils.isAssignable(Short.class, Byte.TYPE, true));
+ assertTrue("short -> short", ClassUtils.isAssignable(Short.class, Short.TYPE, true));
+ assertTrue("short -> int", ClassUtils.isAssignable(Short.class, Integer.TYPE, true));
+ assertTrue("short -> long", ClassUtils.isAssignable(Short.class, Long.TYPE, true));
+ assertTrue("short -> float", ClassUtils.isAssignable(Short.class, Float.TYPE, true));
+ assertTrue("short -> double", ClassUtils.isAssignable(Short.class, Double.TYPE, true));
+ assertFalse("short -> boolean", ClassUtils.isAssignable(Short.class, Boolean.TYPE, true));
+
+ // test char conversions
+ assertTrue("char -> char", ClassUtils.isAssignable(Character.class, Character.TYPE, true));
+ assertFalse("char -> byte", ClassUtils.isAssignable(Character.class, Byte.TYPE, true));
+ assertFalse("char -> short", ClassUtils.isAssignable(Character.class, Short.TYPE, true));
+ assertTrue("char -> int", ClassUtils.isAssignable(Character.class, Integer.TYPE, true));
+ assertTrue("char -> long", ClassUtils.isAssignable(Character.class, Long.TYPE, true));
+ assertTrue("char -> float", ClassUtils.isAssignable(Character.class, Float.TYPE, true));
+ assertTrue("char -> double", ClassUtils.isAssignable(Character.class, Double.TYPE, true));
+ assertFalse("char -> boolean", ClassUtils.isAssignable(Character.class, Boolean.TYPE, true));
+
+ // test int conversions
+ assertFalse("int -> char", ClassUtils.isAssignable(Integer.class, Character.TYPE, true));
+ assertFalse("int -> byte", ClassUtils.isAssignable(Integer.class, Byte.TYPE, true));
+ assertFalse("int -> short", ClassUtils.isAssignable(Integer.class, Short.TYPE, true));
+ assertTrue("int -> int", ClassUtils.isAssignable(Integer.class, Integer.TYPE, true));
+ assertTrue("int -> long", ClassUtils.isAssignable(Integer.class, Long.TYPE, true));
+ assertTrue("int -> float", ClassUtils.isAssignable(Integer.class, Float.TYPE, true));
+ assertTrue("int -> double", ClassUtils.isAssignable(Integer.class, Double.TYPE, true));
+ assertFalse("int -> boolean", ClassUtils.isAssignable(Integer.class, Boolean.TYPE, true));
+
+ // test long conversions
+ assertFalse("long -> char", ClassUtils.isAssignable(Long.class, Character.TYPE, true));
+ assertFalse("long -> byte", ClassUtils.isAssignable(Long.class, Byte.TYPE, true));
+ assertFalse("long -> short", ClassUtils.isAssignable(Long.class, Short.TYPE, true));
+ assertFalse("long -> int", ClassUtils.isAssignable(Long.class, Integer.TYPE, true));
+ assertTrue("long -> long", ClassUtils.isAssignable(Long.class, Long.TYPE, true));
+ assertTrue("long -> float", ClassUtils.isAssignable(Long.class, Float.TYPE, true));
+ assertTrue("long -> double", ClassUtils.isAssignable(Long.class, Double.TYPE, true));
+ assertFalse("long -> boolean", ClassUtils.isAssignable(Long.class, Boolean.TYPE, true));
+
+ // test float conversions
+ assertFalse("float -> char", ClassUtils.isAssignable(Float.class, Character.TYPE, true));
+ assertFalse("float -> byte", ClassUtils.isAssignable(Float.class, Byte.TYPE, true));
+ assertFalse("float -> short", ClassUtils.isAssignable(Float.class, Short.TYPE, true));
+ assertFalse("float -> int", ClassUtils.isAssignable(Float.class, Integer.TYPE, true));
+ assertFalse("float -> long", ClassUtils.isAssignable(Float.class, Long.TYPE, true));
+ assertTrue("float -> float", ClassUtils.isAssignable(Float.class, Float.TYPE, true));
+ assertTrue("float -> double", ClassUtils.isAssignable(Float.class, Double.TYPE, true));
+ assertFalse("float -> boolean", ClassUtils.isAssignable(Float.class, Boolean.TYPE, true));
+
+ // test double conversions
+ assertFalse("double -> char", ClassUtils.isAssignable(Double.class, Character.TYPE, true));
+ assertFalse("double -> byte", ClassUtils.isAssignable(Double.class, Byte.TYPE, true));
+ assertFalse("double -> short", ClassUtils.isAssignable(Double.class, Short.TYPE, true));
+ assertFalse("double -> int", ClassUtils.isAssignable(Double.class, Integer.TYPE, true));
+ assertFalse("double -> long", ClassUtils.isAssignable(Double.class, Long.TYPE, true));
+ assertFalse("double -> float", ClassUtils.isAssignable(Double.class, Float.TYPE, true));
+ assertTrue("double -> double", ClassUtils.isAssignable(Double.class, Double.TYPE, true));
+ assertFalse("double -> boolean", ClassUtils.isAssignable(Double.class, Boolean.TYPE, true));
+
+ // test boolean conversions
+ assertFalse("boolean -> char", ClassUtils.isAssignable(Boolean.class, Character.TYPE, true));
+ assertFalse("boolean -> byte", ClassUtils.isAssignable(Boolean.class, Byte.TYPE, true));
+ assertFalse("boolean -> short", ClassUtils.isAssignable(Boolean.class, Short.TYPE, true));
+ assertFalse("boolean -> int", ClassUtils.isAssignable(Boolean.class, Integer.TYPE, true));
+ assertFalse("boolean -> long", ClassUtils.isAssignable(Boolean.class, Long.TYPE, true));
+ assertFalse("boolean -> float", ClassUtils.isAssignable(Boolean.class, Float.TYPE, true));
+ assertFalse("boolean -> double", ClassUtils.isAssignable(Boolean.class, Double.TYPE, true));
+ assertTrue("boolean -> boolean", ClassUtils.isAssignable(Boolean.class, Boolean.TYPE, true));
+ }
+
+ public void testIsPrimitiveOrWrapper() {
+
+ // test primitive wrapper classes
+ assertTrue("Boolean.class", ClassUtils.isPrimitiveOrWrapper(Boolean.class));
+ assertTrue("Byte.class", ClassUtils.isPrimitiveOrWrapper(Byte.class));
+ assertTrue("Character.class", ClassUtils.isPrimitiveOrWrapper(Character.class));
+ assertTrue("Short.class", ClassUtils.isPrimitiveOrWrapper(Short.class));
+ assertTrue("Integer.class", ClassUtils.isPrimitiveOrWrapper(Integer.class));
+ assertTrue("Long.class", ClassUtils.isPrimitiveOrWrapper(Long.class));
+ assertTrue("Double.class", ClassUtils.isPrimitiveOrWrapper(Double.class));
+ assertTrue("Float.class", ClassUtils.isPrimitiveOrWrapper(Float.class));
+
+ // test primitive classes
+ assertTrue("boolean", ClassUtils.isPrimitiveOrWrapper(Boolean.TYPE));
+ assertTrue("byte", ClassUtils.isPrimitiveOrWrapper(Byte.TYPE));
+ assertTrue("char", ClassUtils.isPrimitiveOrWrapper(Character.TYPE));
+ assertTrue("short", ClassUtils.isPrimitiveOrWrapper(Short.TYPE));
+ assertTrue("int", ClassUtils.isPrimitiveOrWrapper(Integer.TYPE));
+ assertTrue("long", ClassUtils.isPrimitiveOrWrapper(Long.TYPE));
+ assertTrue("double", ClassUtils.isPrimitiveOrWrapper(Double.TYPE));
+ assertTrue("float", ClassUtils.isPrimitiveOrWrapper(Float.TYPE));
+ assertTrue("Void.TYPE", ClassUtils.isPrimitiveOrWrapper(Void.TYPE));
+
+ // others
+ assertFalse("null", ClassUtils.isPrimitiveOrWrapper(null));
+ assertFalse("Void.class", ClassUtils.isPrimitiveOrWrapper(Void.class));
+ assertFalse("String.class", ClassUtils.isPrimitiveOrWrapper(String.class));
+ assertFalse("this.getClass()", ClassUtils.isPrimitiveOrWrapper(this.getClass()));
+ }
+
+ public void testIsPrimitiveWrapper() {
+
+ // test primitive wrapper classes
+ assertTrue("Boolean.class", ClassUtils.isPrimitiveWrapper(Boolean.class));
+ assertTrue("Byte.class", ClassUtils.isPrimitiveWrapper(Byte.class));
+ assertTrue("Character.class", ClassUtils.isPrimitiveWrapper(Character.class));
+ assertTrue("Short.class", ClassUtils.isPrimitiveWrapper(Short.class));
+ assertTrue("Integer.class", ClassUtils.isPrimitiveWrapper(Integer.class));
+ assertTrue("Long.class", ClassUtils.isPrimitiveWrapper(Long.class));
+ assertTrue("Double.class", ClassUtils.isPrimitiveWrapper(Double.class));
+ assertTrue("Float.class", ClassUtils.isPrimitiveWrapper(Float.class));
+
+ // test primitive classes
+ assertFalse("boolean", ClassUtils.isPrimitiveWrapper(Boolean.TYPE));
+ assertFalse("byte", ClassUtils.isPrimitiveWrapper(Byte.TYPE));
+ assertFalse("char", ClassUtils.isPrimitiveWrapper(Character.TYPE));
+ assertFalse("short", ClassUtils.isPrimitiveWrapper(Short.TYPE));
+ assertFalse("int", ClassUtils.isPrimitiveWrapper(Integer.TYPE));
+ assertFalse("long", ClassUtils.isPrimitiveWrapper(Long.TYPE));
+ assertFalse("double", ClassUtils.isPrimitiveWrapper(Double.TYPE));
+ assertFalse("float", ClassUtils.isPrimitiveWrapper(Float.TYPE));
+
+ // others
+ assertFalse("null", ClassUtils.isPrimitiveWrapper(null));
+ assertFalse("Void.class", ClassUtils.isPrimitiveWrapper(Void.class));
+ assertFalse("Void.TYPE", ClassUtils.isPrimitiveWrapper(Void.TYPE));
+ assertFalse("String.class", ClassUtils.isPrimitiveWrapper(String.class));
+ assertFalse("this.getClass()", ClassUtils.isPrimitiveWrapper(this.getClass()));
+ }
+
+ public void testPrimitiveToWrapper() {
+
+ // test primitive classes
+ assertEquals("boolean -> Boolean.class",
+ Boolean.class, ClassUtils.primitiveToWrapper(Boolean.TYPE));
+ assertEquals("byte -> Byte.class",
+ Byte.class, ClassUtils.primitiveToWrapper(Byte.TYPE));
+ assertEquals("char -> Character.class",
+ Character.class, ClassUtils.primitiveToWrapper(Character.TYPE));
+ assertEquals("short -> Short.class",
+ Short.class, ClassUtils.primitiveToWrapper(Short.TYPE));
+ assertEquals("int -> Integer.class",
+ Integer.class, ClassUtils.primitiveToWrapper(Integer.TYPE));
+ assertEquals("long -> Long.class",
+ Long.class, ClassUtils.primitiveToWrapper(Long.TYPE));
+ assertEquals("double -> Double.class",
+ Double.class, ClassUtils.primitiveToWrapper(Double.TYPE));
+ assertEquals("float -> Float.class",
+ Float.class, ClassUtils.primitiveToWrapper(Float.TYPE));
+
+ // test a few other classes
+ assertEquals("String.class -> String.class",
+ String.class, ClassUtils.primitiveToWrapper(String.class));
+ assertEquals("ClassUtils.class -> ClassUtils.class",
+ org.apache.commons.lang3.ClassUtils.class,
+ ClassUtils.primitiveToWrapper(org.apache.commons.lang3.ClassUtils.class));
+ assertEquals("Void.TYPE -> Void.TYPE",
+ Void.TYPE, ClassUtils.primitiveToWrapper(Void.TYPE));
+
+ // test null
+ assertNull("null -> null",
+ ClassUtils.primitiveToWrapper(null));
+ }
+
+ public void testPrimitivesToWrappers() {
+ // test null
+// assertNull("null -> null", ClassUtils.primitivesToWrappers(null)); // generates warning
+ assertNull("null -> null", ClassUtils.primitivesToWrappers((Class>[]) null)); // equivalent cast to avoid warning
+ // Other possible casts for null
+ assertTrue("empty -> empty", Arrays.equals(ArrayUtils.EMPTY_CLASS_ARRAY, ClassUtils.primitivesToWrappers()));
+ Class>[] castNull = ClassUtils.primitivesToWrappers((Class>)null); // == new Class>[]{null}
+ assertTrue("(Class>)null -> [null]", Arrays.equals(new Class>[]{null}, castNull));
+ // test empty array is returned unchanged
+ // TODO this is not documented
+ assertEquals("empty -> empty",
+ ArrayUtils.EMPTY_CLASS_ARRAY, ClassUtils.primitivesToWrappers(ArrayUtils.EMPTY_CLASS_ARRAY));
+
+ // test an array of various classes
+ final Class>[] primitives = new Class[] {
+ Boolean.TYPE, Byte.TYPE, Character.TYPE, Short.TYPE,
+ Integer.TYPE, Long.TYPE, Double.TYPE, Float.TYPE,
+ String.class, ClassUtils.class
+ };
+ Class>[] wrappers= ClassUtils.primitivesToWrappers(primitives);
+
+ for (int i=0; i < primitives.length; i++) {
+ // test each returned wrapper
+ Class> primitive = primitives[i];
+ Class> expectedWrapper = ClassUtils.primitiveToWrapper(primitive);
+
+ assertEquals(primitive + " -> " + expectedWrapper, expectedWrapper, wrappers[i]);
+ }
+
+ // test an array of no primitive classes
+ final Class>[] noPrimitives = new Class[] {
+ String.class, ClassUtils.class, Void.TYPE
+ };
+ // This used to return the exact same array, but no longer does.
+ assertNotSame("unmodified", noPrimitives, ClassUtils.primitivesToWrappers(noPrimitives));
+ }
+
+ public void testWrapperToPrimitive() {
+ // an array with classes to convert
+ final Class>[] primitives = {
+ Boolean.TYPE, Byte.TYPE, Character.TYPE, Short.TYPE,
+ Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE
+ };
+ for (Class> primitive : primitives) {
+ Class> wrapperCls = ClassUtils.primitiveToWrapper(primitive);
+ assertFalse("Still primitive", wrapperCls.isPrimitive());
+ assertEquals(wrapperCls + " -> " + primitive, primitive,
+ ClassUtils.wrapperToPrimitive(wrapperCls));
+ }
+ }
+
+ public void testWrapperToPrimitiveNoWrapper() {
+ assertNull("Wrong result for non wrapper class", ClassUtils.wrapperToPrimitive(String.class));
+ }
+
+ public void testWrapperToPrimitiveNull() {
+ assertNull("Wrong result for null class", ClassUtils.wrapperToPrimitive(null));
+ }
+
+ public void testWrappersToPrimitives() {
+ // an array with classes to test
+ final Class>[] classes = {
+ Boolean.class, Byte.class, Character.class, Short.class,
+ Integer.class, Long.class, Float.class, Double.class,
+ String.class, ClassUtils.class, null
+ };
+
+ Class>[] primitives = ClassUtils.wrappersToPrimitives(classes);
+ // now test the result
+ assertEquals("Wrong length of result array", classes.length, primitives.length);
+ for (int i = 0; i < classes.length; i++) {
+ Class> expectedPrimitive = ClassUtils.wrapperToPrimitive(classes[i]);
+ assertEquals(classes[i] + " -> " + expectedPrimitive, expectedPrimitive,
+ primitives[i]);
+ }
+ }
+
+ public void testWrappersToPrimitivesNull() {
+// assertNull("Wrong result for null input", ClassUtils.wrappersToPrimitives(null)); // generates warning
+ assertNull("Wrong result for null input", ClassUtils.wrappersToPrimitives((Class>[]) null)); // equivalent cast
+ // Other possible casts for null
+ assertTrue("empty -> empty", Arrays.equals(ArrayUtils.EMPTY_CLASS_ARRAY, ClassUtils.wrappersToPrimitives()));
+ Class>[] castNull = ClassUtils.wrappersToPrimitives((Class>)null); // == new Class>[]{null}
+ assertTrue("(Class>)null -> [null]", Arrays.equals(new Class>[]{null}, castNull));
+}
+
+ public void testWrappersToPrimitivesEmpty() {
+ Class>[] empty = new Class[0];
+ assertEquals("Wrong result for empty input", empty, ClassUtils.wrappersToPrimitives(empty));
+ }
+
+ public void testGetClassClassNotFound() throws Exception {
+ assertGetClassThrowsClassNotFound( "bool" );
+ assertGetClassThrowsClassNotFound( "bool[]" );
+ assertGetClassThrowsClassNotFound( "integer[]" );
+ }
+
+ public void testGetClassInvalidArguments() throws Exception {
+ assertGetClassThrowsNullPointerException( null );
+ assertGetClassThrowsClassNotFound( "[][][]" );
+ assertGetClassThrowsClassNotFound( "[[]" );
+ assertGetClassThrowsClassNotFound( "[" );
+ assertGetClassThrowsClassNotFound( "java.lang.String][" );
+ assertGetClassThrowsClassNotFound( ".hello.world" );
+ assertGetClassThrowsClassNotFound( "hello..world" );
+ }
+
+ public void testWithInterleavingWhitespace() throws ClassNotFoundException {
+ assertEquals( int[].class, ClassUtils.getClass( " int [ ] " ) );
+ assertEquals( long[].class, ClassUtils.getClass( "\rlong\t[\n]\r" ) );
+ assertEquals( short[].class, ClassUtils.getClass( "\tshort \t\t[]" ) );
+ assertEquals( byte[].class, ClassUtils.getClass( "byte[\t\t\n\r] " ) );
+ }
+
+ public void testGetInnerClass() throws ClassNotFoundException {
+ assertEquals( Inner.DeeplyNested.class, ClassUtils.getClass( "org.apache.commons.lang3.ClassUtilsTest.Inner.DeeplyNested" ) );
+ assertEquals( Inner.DeeplyNested.class, ClassUtils.getClass( "org.apache.commons.lang3.ClassUtilsTest.Inner$DeeplyNested" ) );
+ assertEquals( Inner.DeeplyNested.class, ClassUtils.getClass( "org.apache.commons.lang3.ClassUtilsTest$Inner$DeeplyNested" ) );
+ assertEquals( Inner.DeeplyNested.class, ClassUtils.getClass( "org.apache.commons.lang3.ClassUtilsTest$Inner.DeeplyNested" ) );
+ }
+
+ public void testGetClassByNormalNameArrays() throws ClassNotFoundException {
+ assertEquals( int[].class, ClassUtils.getClass( "int[]" ) );
+ assertEquals( long[].class, ClassUtils.getClass( "long[]" ) );
+ assertEquals( short[].class, ClassUtils.getClass( "short[]" ) );
+ assertEquals( byte[].class, ClassUtils.getClass( "byte[]" ) );
+ assertEquals( char[].class, ClassUtils.getClass( "char[]" ) );
+ assertEquals( float[].class, ClassUtils.getClass( "float[]" ) );
+ assertEquals( double[].class, ClassUtils.getClass( "double[]" ) );
+ assertEquals( boolean[].class, ClassUtils.getClass( "boolean[]" ) );
+ assertEquals( String[].class, ClassUtils.getClass( "java.lang.String[]" ) );
+ assertEquals( java.util.Map.Entry[].class, ClassUtils.getClass( "java.util.Map.Entry[]" ) );
+ assertEquals( java.util.Map.Entry[].class, ClassUtils.getClass( "java.util.Map$Entry[]" ) );
+ assertEquals( java.util.Map.Entry[].class, ClassUtils.getClass( "[Ljava.util.Map.Entry;" ) );
+ assertEquals( java.util.Map.Entry[].class, ClassUtils.getClass( "[Ljava.util.Map$Entry;" ) );
+ }
+
+ public void testGetClassByNormalNameArrays2D() throws ClassNotFoundException {
+ assertEquals( int[][].class, ClassUtils.getClass( "int[][]" ) );
+ assertEquals( long[][].class, ClassUtils.getClass( "long[][]" ) );
+ assertEquals( short[][].class, ClassUtils.getClass( "short[][]" ) );
+ assertEquals( byte[][].class, ClassUtils.getClass( "byte[][]" ) );
+ assertEquals( char[][].class, ClassUtils.getClass( "char[][]" ) );
+ assertEquals( float[][].class, ClassUtils.getClass( "float[][]" ) );
+ assertEquals( double[][].class, ClassUtils.getClass( "double[][]" ) );
+ assertEquals( boolean[][].class, ClassUtils.getClass( "boolean[][]" ) );
+ assertEquals( String[][].class, ClassUtils.getClass( "java.lang.String[][]" ) );
+ }
+
+ public void testGetClassWithArrayClasses2D() throws Exception {
+ assertGetClassReturnsClass( String[][].class );
+ assertGetClassReturnsClass( int[][].class );
+ assertGetClassReturnsClass( long[][].class );
+ assertGetClassReturnsClass( short[][].class );
+ assertGetClassReturnsClass( byte[][].class );
+ assertGetClassReturnsClass( char[][].class );
+ assertGetClassReturnsClass( float[][].class );
+ assertGetClassReturnsClass( double[][].class );
+ assertGetClassReturnsClass( boolean[][].class );
+ }
+
+ public void testGetClassWithArrayClasses() throws Exception {
+ assertGetClassReturnsClass( String[].class );
+ assertGetClassReturnsClass( int[].class );
+ assertGetClassReturnsClass( long[].class );
+ assertGetClassReturnsClass( short[].class );
+ assertGetClassReturnsClass( byte[].class );
+ assertGetClassReturnsClass( char[].class );
+ assertGetClassReturnsClass( float[].class );
+ assertGetClassReturnsClass( double[].class );
+ assertGetClassReturnsClass( boolean[].class );
+ }
+
+ public void testGetClassRawPrimitives() throws ClassNotFoundException {
+ assertEquals( int.class, ClassUtils.getClass( "int" ) );
+ assertEquals( long.class, ClassUtils.getClass( "long" ) );
+ assertEquals( short.class, ClassUtils.getClass( "short" ) );
+ assertEquals( byte.class, ClassUtils.getClass( "byte" ) );
+ assertEquals( char.class, ClassUtils.getClass( "char" ) );
+ assertEquals( float.class, ClassUtils.getClass( "float" ) );
+ assertEquals( double.class, ClassUtils.getClass( "double" ) );
+ assertEquals( boolean.class, ClassUtils.getClass( "boolean" ) );
+ }
+
+ private void assertGetClassReturnsClass( Class> c ) throws Exception {
+ assertEquals( c, ClassUtils.getClass( c.getName() ) );
+ }
+
+ private void assertGetClassThrowsException( String className, Class> exceptionType ) throws Exception {
+ try {
+ ClassUtils.getClass( className );
+ fail( "ClassUtils.getClass() should fail with an exception of type " + exceptionType.getName() + " when given class name \"" + className + "\"." );
+ }
+ catch( Exception e ) {
+ assertTrue( exceptionType.isAssignableFrom( e.getClass() ) );
+ }
+ }
+
+ private void assertGetClassThrowsNullPointerException( String className ) throws Exception {
+ assertGetClassThrowsException( className, NullPointerException.class );
+ }
+
+ private void assertGetClassThrowsClassNotFound( String className ) throws Exception {
+ assertGetClassThrowsException( className, ClassNotFoundException.class );
+ }
+
+ // Show the Java bug: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4071957
+ // We may have to delete this if a JDK fixes the bug.
+ public void testShowJavaBug() throws Exception {
+ // Tests with Collections$UnmodifiableSet
+ Set> set = Collections.unmodifiableSet(new HashSet());
+ Method isEmptyMethod = set.getClass().getMethod("isEmpty", new Class[0]);
+ try {
+ isEmptyMethod.invoke(set, new Object[0]);
+ fail("Failed to throw IllegalAccessException as expected");
+ } catch(IllegalAccessException iae) {
+ // expected
+ }
+ }
+
+ public void testGetPublicMethod() throws Exception {
+ // Tests with Collections$UnmodifiableSet
+ Set> set = Collections.unmodifiableSet(new HashSet());
+ Method isEmptyMethod = ClassUtils.getPublicMethod(set.getClass(), "isEmpty", new Class[0]);
+ assertTrue(Modifier.isPublic(isEmptyMethod.getDeclaringClass().getModifiers()));
+
+ try {
+ isEmptyMethod.invoke(set, new Object[0]);
+ } catch(java.lang.IllegalAccessException iae) {
+ fail("Should not have thrown IllegalAccessException");
+ }
+
+ // Tests with a public Class
+ Method toStringMethod = ClassUtils.getPublicMethod(Object.class, "toString", new Class[0]);
+ assertEquals(Object.class.getMethod("toString", new Class[0]), toStringMethod);
+ }
+
+ public void testToClass_object() {
+// assertNull(ClassUtils.toClass(null)); // generates warning
+ assertNull(ClassUtils.toClass((Object[]) null)); // equivalent explicit cast
+
+ // Additional varargs tests
+ assertTrue("empty -> empty", Arrays.equals(ArrayUtils.EMPTY_CLASS_ARRAY, ClassUtils.toClass()));
+ Class>[] castNull = ClassUtils.toClass((Object) null); // == new Object[]{null}
+ assertTrue("(Object)null -> [null]", Arrays.equals(new Object[]{null}, castNull));
+
+ assertSame(ArrayUtils.EMPTY_CLASS_ARRAY, ClassUtils.toClass(ArrayUtils.EMPTY_OBJECT_ARRAY));
+
+ assertTrue(Arrays.equals(new Class[] { String.class, Integer.class, Double.class },
+ ClassUtils.toClass(new Object[] { "Test", Integer.valueOf(1), Double.valueOf(99d) })));
+
+ assertTrue(Arrays.equals(new Class[] { String.class, null, Double.class },
+ ClassUtils.toClass(new Object[] { "Test", null, Double.valueOf(99d) })));
+ }
+
+ public void test_getShortCanonicalName_Object() {
+ assertEquals("", ClassUtils.getShortCanonicalName(null, ""));
+ assertEquals("ClassUtils", ClassUtils.getShortCanonicalName(new ClassUtils(), ""));
+ assertEquals("ClassUtils[]", ClassUtils.getShortCanonicalName(new ClassUtils[0], ""));
+ assertEquals("ClassUtils[][]", ClassUtils.getShortCanonicalName(new ClassUtils[0][0], ""));
+ assertEquals("int[]", ClassUtils.getShortCanonicalName(new int[0], ""));
+ assertEquals("int[][]", ClassUtils.getShortCanonicalName(new int[0][0], ""));
+
+ // Inner types
+ class Named extends Object {}
+ assertEquals("ClassUtilsTest.6", ClassUtils.getShortCanonicalName(new Object(){}, ""));
+ assertEquals("ClassUtilsTest.5Named", ClassUtils.getShortCanonicalName(new Named(), ""));
+ assertEquals("ClassUtilsTest.Inner", ClassUtils.getShortCanonicalName(new Inner(), ""));
+ }
+
+ public void test_getShortCanonicalName_Class() {
+ assertEquals("ClassUtils", ClassUtils.getShortCanonicalName(ClassUtils.class));
+ assertEquals("ClassUtils[]", ClassUtils.getShortCanonicalName(ClassUtils[].class));
+ assertEquals("ClassUtils[][]", ClassUtils.getShortCanonicalName(ClassUtils[][].class));
+ assertEquals("int[]", ClassUtils.getShortCanonicalName(int[].class));
+ assertEquals("int[][]", ClassUtils.getShortCanonicalName(int[][].class));
+
+ // Inner types
+ class Named extends Object {}
+ assertEquals("ClassUtilsTest.7", ClassUtils.getShortCanonicalName(new Object(){}.getClass()));
+ assertEquals("ClassUtilsTest.6Named", ClassUtils.getShortCanonicalName(Named.class));
+ assertEquals("ClassUtilsTest.Inner", ClassUtils.getShortCanonicalName(Inner.class));
+ }
+
+ public void test_getShortCanonicalName_String() {
+ assertEquals("ClassUtils", ClassUtils.getShortCanonicalName("org.apache.commons.lang3.ClassUtils"));
+ assertEquals("ClassUtils[]", ClassUtils.getShortCanonicalName("[Lorg.apache.commons.lang3.ClassUtils;"));
+ assertEquals("ClassUtils[][]", ClassUtils.getShortCanonicalName("[[Lorg.apache.commons.lang3.ClassUtils;"));
+ assertEquals("ClassUtils[]", ClassUtils.getShortCanonicalName("org.apache.commons.lang3.ClassUtils[]"));
+ assertEquals("ClassUtils[][]", ClassUtils.getShortCanonicalName("org.apache.commons.lang3.ClassUtils[][]"));
+ assertEquals("int[]", ClassUtils.getShortCanonicalName("[I"));
+ assertEquals("int[][]", ClassUtils.getShortCanonicalName("[[I"));
+ assertEquals("int[]", ClassUtils.getShortCanonicalName("int[]"));
+ assertEquals("int[][]", ClassUtils.getShortCanonicalName("int[][]"));
+
+ // Inner types
+ assertEquals("ClassUtilsTest.6", ClassUtils.getShortCanonicalName("org.apache.commons.lang3.ClassUtilsTest$6"));
+ assertEquals("ClassUtilsTest.5Named", ClassUtils.getShortCanonicalName("org.apache.commons.lang3.ClassUtilsTest$5Named"));
+ assertEquals("ClassUtilsTest.Inner", ClassUtils.getShortCanonicalName("org.apache.commons.lang3.ClassUtilsTest$Inner"));
+ }
+
+ public void test_getPackageCanonicalName_Object() {
+ assertEquals("", ClassUtils.getPackageCanonicalName(null, ""));
+ assertEquals("org.apache.commons.lang3", ClassUtils.getPackageCanonicalName(new ClassUtils(), ""));
+ assertEquals("org.apache.commons.lang3", ClassUtils.getPackageCanonicalName(new ClassUtils[0], ""));
+ assertEquals("org.apache.commons.lang3", ClassUtils.getPackageCanonicalName(new ClassUtils[0][0], ""));
+ assertEquals("", ClassUtils.getPackageCanonicalName(new int[0], ""));
+ assertEquals("", ClassUtils.getPackageCanonicalName(new int[0][0], ""));
+
+ // Inner types
+ class Named extends Object {}
+ assertEquals("org.apache.commons.lang3", ClassUtils.getPackageCanonicalName(new Object(){}, ""));
+ assertEquals("org.apache.commons.lang3", ClassUtils.getPackageCanonicalName(new Named(), ""));
+ assertEquals("org.apache.commons.lang3", ClassUtils.getPackageCanonicalName(new Inner(), ""));
+ }
+
+ public void test_getPackageCanonicalName_Class() {
+ assertEquals("org.apache.commons.lang3", ClassUtils.getPackageCanonicalName(ClassUtils.class));
+ assertEquals("org.apache.commons.lang3", ClassUtils.getPackageCanonicalName(ClassUtils[].class));
+ assertEquals("org.apache.commons.lang3", ClassUtils.getPackageCanonicalName(ClassUtils[][].class));
+ assertEquals("", ClassUtils.getPackageCanonicalName(int[].class));
+ assertEquals("", ClassUtils.getPackageCanonicalName(int[][].class));
+
+ // Inner types
+ class Named extends Object {}
+ assertEquals("org.apache.commons.lang3", ClassUtils.getPackageCanonicalName(new Object(){}.getClass()));
+ assertEquals("org.apache.commons.lang3", ClassUtils.getPackageCanonicalName(Named.class));
+ assertEquals("org.apache.commons.lang3", ClassUtils.getPackageCanonicalName(Inner.class));
+ }
+
+ public void test_getPackageCanonicalName_String() {
+ assertEquals("org.apache.commons.lang3",
+ ClassUtils.getPackageCanonicalName("org.apache.commons.lang3.ClassUtils"));
+ assertEquals("org.apache.commons.lang3",
+ ClassUtils.getPackageCanonicalName("[Lorg.apache.commons.lang3.ClassUtils;"));
+ assertEquals("org.apache.commons.lang3",
+ ClassUtils.getPackageCanonicalName("[[Lorg.apache.commons.lang3.ClassUtils;"));
+ assertEquals("org.apache.commons.lang3",
+ ClassUtils.getPackageCanonicalName("org.apache.commons.lang3.ClassUtils[]"));
+ assertEquals("org.apache.commons.lang3",
+ ClassUtils.getPackageCanonicalName("org.apache.commons.lang3.ClassUtils[][]"));
+ assertEquals("", ClassUtils.getPackageCanonicalName("[I"));
+ assertEquals("", ClassUtils.getPackageCanonicalName("[[I"));
+ assertEquals("", ClassUtils.getPackageCanonicalName("int[]"));
+ assertEquals("", ClassUtils.getPackageCanonicalName("int[][]"));
+
+ // Inner types
+ assertEquals("org.apache.commons.lang3", ClassUtils.getPackageCanonicalName("org.apache.commons.lang3.ClassUtilsTest$6"));
+ assertEquals("org.apache.commons.lang3", ClassUtils.getPackageCanonicalName("org.apache.commons.lang3.ClassUtilsTest$5Named"));
+ assertEquals("org.apache.commons.lang3", ClassUtils.getPackageCanonicalName("org.apache.commons.lang3.ClassUtilsTest$Inner"));
+ }
+
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/EnumUtils.java b/ApacheCommonsLang/org/apache/commons/lang3/EnumUtils.java
new file mode 100644
index 0000000..c72899d
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/EnumUtils.java
@@ -0,0 +1,208 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+package org.apache.commons.lang3;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.EnumSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Utility library to provide helper methods for Java enums.
+ *
+ * #ThreadSafe#
+ *
+ * @since 3.0
+ * @version $Id: EnumUtils.java 1299413 2012-03-11 17:57:40Z ggregory $
+ */
+public class EnumUtils {
+
+ /**
+ * This constructor is public to permit tools that require a JavaBean
+ * instance to operate.
+ */
+ public EnumUtils() {
+ }
+
+ /**
+ * Gets the {@code Map} of enums by name.
+ *
+ * This method is useful when you need a map of enums by name.
+ *
+ * @param the type of the enumeration
+ * @param enumClass the class of the enum to query, not null
+ * @return the modifiable map of enum names to enums, never null
+ */
+ public static > Map getEnumMap(Class enumClass) {
+ Map map = new LinkedHashMap();
+ for (E e: enumClass.getEnumConstants()) {
+ map.put(e.name(), e);
+ }
+ return map;
+ }
+
+ /**
+ * Gets the {@code List} of enums.
+ *
+ * This method is useful when you need a list of enums rather than an array.
+ *
+ * @param the type of the enumeration
+ * @param enumClass the class of the enum to query, not null
+ * @return the modifiable list of enums, never null
+ */
+ public static > List getEnumList(Class enumClass) {
+ return new ArrayList(Arrays.asList(enumClass.getEnumConstants()));
+ }
+
+ /**
+ * Checks if the specified name is a valid enum for the class.
+ *
+ * This method differs from {@link Enum#valueOf} in that checks if the name is
+ * a valid enum without needing to catch the exception.
+ *
+ * @param the type of the enumeration
+ * @param enumClass the class of the enum to query, not null
+ * @param enumName the enum name, null returns false
+ * @return true if the enum name is valid, otherwise false
+ */
+ public static > boolean isValidEnum(Class enumClass, String enumName) {
+ if (enumName == null) {
+ return false;
+ }
+ try {
+ Enum.valueOf(enumClass, enumName);
+ return true;
+ } catch (IllegalArgumentException ex) {
+ return false;
+ }
+ }
+
+ /**
+ * Gets the enum for the class, returning {@code null} if not found.
+ *
+ * This method differs from {@link Enum#valueOf} in that it does not throw an exception
+ * for an invalid enum name.
+ *
+ * @param the type of the enumeration
+ * @param enumClass the class of the enum to query, not null
+ * @param enumName the enum name, null returns null
+ * @return the enum, null if not found
+ */
+ public static > E getEnum(Class enumClass, String enumName) {
+ if (enumName == null) {
+ return null;
+ }
+ try {
+ return Enum.valueOf(enumClass, enumName);
+ } catch (IllegalArgumentException ex) {
+ return null;
+ }
+ }
+
+ /**
+ * Creates a long bit vector representation of the given subset of an Enum.
+ *
+ * This generates a value that is usable by {@link EnumUtils#processBitVector}.
+ *
+ * Do not use this method if you have more than 64 values in your Enum, as this
+ * would create a value greater than a long can hold.
+ *
+ * @param enumClass the class of the enum we are working with, not {@code null}
+ * @param values the values we want to convert, not {@code null}
+ * @param the type of the enumeration
+ * @return a long whose binary value represents the given set of enum values.
+ * @throws NullPointerException if {@code enumClass} or {@code values} is {@code null}
+ * @throws IllegalArgumentException if {@code enumClass} is not an enum class or has more than 64 values
+ * @since 3.0.1
+ */
+ public static > long generateBitVector(Class enumClass, Iterable values) {
+ checkBitVectorable(enumClass);
+ Validate.notNull(values);
+ long total = 0;
+ for (E constant : values) {
+ total |= 1 << constant.ordinal();
+ }
+ return total;
+ }
+
+ /**
+ * Creates a long bit vector representation of the given array of Enum values.
+ *
+ * This generates a value that is usable by {@link EnumUtils#processBitVector}.
+ *
+ * Do not use this method if you have more than 64 values in your Enum, as this
+ * would create a value greater than a long can hold.
+ *
+ * @param enumClass the class of the enum we are working with, not {@code null}
+ * @param values the values we want to convert, not {@code null}
+ * @param the type of the enumeration
+ * @return a long whose binary value represents the given set of enum values.
+ * @throws NullPointerException if {@code enumClass} or {@code values} is {@code null}
+ * @throws IllegalArgumentException if {@code enumClass} is not an enum class or has more than 64 values
+ * @since 3.0.1
+ */
+ public static > long generateBitVector(Class enumClass, E... values) {
+ Validate.noNullElements(values);
+ return generateBitVector(enumClass, Arrays. asList(values));
+ }
+
+ /**
+ * Convert a long value created by {@link EnumUtils#generateBitVector} into the set of
+ * enum values that it represents.
+ *
+ * If you store this value, beware any changes to the enum that would affect ordinal values.
+ * @param enumClass the class of the enum we are working with, not {@code null}
+ * @param value the long value representation of a set of enum values
+ * @param the type of the enumeration
+ * @return a set of enum values
+ * @throws NullPointerException if {@code enumClass} is {@code null}
+ * @throws IllegalArgumentException if {@code enumClass} is not an enum class or has more than 64 values
+ * @since 3.0.1
+ */
+ public static > EnumSet processBitVector(Class enumClass, long value) {
+ final E[] constants = checkBitVectorable(enumClass).getEnumConstants();
+ final EnumSet results = EnumSet.noneOf(enumClass);
+ for (E constant : constants) {
+ if ((value & 1 << constant.ordinal()) != 0) {
+ results.add(constant);
+ }
+ }
+ return results;
+ }
+
+ /**
+ * Validate that {@code enumClass} is compatible with representation in a {@code long}.
+ * @param the type of the enumeration
+ * @param enumClass to check
+ * @return {@code enumClass}
+ * @throws NullPointerException if {@code enumClass} is {@code null}
+ * @throws IllegalArgumentException if {@code enumClass} is not an enum class or has more than 64 values
+ * @since 3.0.1
+ */
+ private static > Class checkBitVectorable(Class enumClass) {
+ Validate.notNull(enumClass, "EnumClass must be defined.");
+
+ final E[] constants = enumClass.getEnumConstants();
+ Validate.isTrue(constants != null, "%s does not seem to be an Enum type", enumClass);
+ Validate.isTrue(constants.length <= Long.SIZE, "Cannot store %s %s values in %s bits", constants.length,
+ enumClass.getSimpleName(), Long.SIZE);
+
+ return enumClass;
+ }
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/EnumUtilsTest.java b/ApacheCommonsLang/org/apache/commons/lang3/EnumUtilsTest.java
new file mode 100644
index 0000000..5dc91a4
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/EnumUtilsTest.java
@@ -0,0 +1,201 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+package org.apache.commons.lang3;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Test;
+
+/**
+ *
+ * @version $Id: EnumUtilsTest.java 1309910 2012-04-05 15:52:43Z ggregory $
+ */
+public class EnumUtilsTest {
+
+ @Test
+ public void testConstructable() {
+ // enforce public constructor
+ new EnumUtils();
+ }
+
+ @Test
+ public void test_getEnumMap() {
+ Map test = EnumUtils.getEnumMap(Traffic.class);
+ assertEquals( "getEnumMap not created correctly", "{RED=RED, AMBER=AMBER, GREEN=GREEN}", test.toString());
+ assertEquals(3, test.size());
+ assertTrue(test.containsKey("RED"));
+ assertEquals(Traffic.RED, test.get("RED"));
+ assertTrue(test.containsKey("AMBER"));
+ assertEquals(Traffic.AMBER, test.get("AMBER"));
+ assertTrue(test.containsKey("GREEN"));
+ assertEquals(Traffic.GREEN, test.get("GREEN"));
+ assertFalse(test.containsKey("PURPLE"));
+ }
+
+ @Test
+ public void test_getEnumList() {
+ List test = EnumUtils.getEnumList(Traffic.class);
+ assertEquals(3, test.size());
+ assertEquals(Traffic.RED, test.get(0));
+ assertEquals(Traffic.AMBER, test.get(1));
+ assertEquals(Traffic.GREEN, test.get(2));
+ }
+
+ @Test
+ public void test_isEnum() {
+ assertTrue(EnumUtils.isValidEnum(Traffic.class, "RED"));
+ assertTrue(EnumUtils.isValidEnum(Traffic.class, "AMBER"));
+ assertTrue(EnumUtils.isValidEnum(Traffic.class, "GREEN"));
+ assertFalse(EnumUtils.isValidEnum(Traffic.class, "PURPLE"));
+ assertFalse(EnumUtils.isValidEnum(Traffic.class, null));
+ }
+
+ @Test(expected=NullPointerException.class)
+ public void test_isEnum_nullClass() {
+ EnumUtils.isValidEnum((Class) null, "PURPLE");
+ }
+
+ @Test
+ public void test_getEnum() {
+ assertEquals(Traffic.RED, EnumUtils.getEnum(Traffic.class, "RED"));
+ assertEquals(Traffic.AMBER, EnumUtils.getEnum(Traffic.class, "AMBER"));
+ assertEquals(Traffic.GREEN, EnumUtils.getEnum(Traffic.class, "GREEN"));
+ assertEquals(null, EnumUtils.getEnum(Traffic.class, "PURPLE"));
+ assertEquals(null, EnumUtils.getEnum(Traffic.class, null));
+ }
+
+ @Test(expected=NullPointerException.class)
+ public void test_getEnum_nullClass() {
+ EnumUtils.getEnum((Class) null, "PURPLE");
+ }
+
+ @Test(expected=NullPointerException.class)
+ public void test_generateBitVector_nullClass() {
+ EnumUtils.generateBitVector(null, EnumSet.of(Traffic.RED));
+ }
+
+ @Test(expected=NullPointerException.class)
+ public void test_generateBitVector_nullIterable() {
+ EnumUtils.generateBitVector(null, (Iterable) null);
+ }
+
+ @Test(expected=NullPointerException.class)
+ public void test_generateBitVector_nullClassWithArray() {
+ EnumUtils.generateBitVector(null, Traffic.RED);
+ }
+
+ @Test(expected=NullPointerException.class)
+ public void test_generateBitVector_nullArray() {
+ EnumUtils.generateBitVector(null, (Traffic[]) null);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void test_generateBitVector_longClass() {
+ EnumUtils.generateBitVector(TooMany.class, EnumSet.of(TooMany.A1));
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void test_generateBitVector_longClassWithArray() {
+ EnumUtils.generateBitVector(TooMany.class, TooMany.A1);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test(expected=IllegalArgumentException.class)
+ public void test_generateBitVector_nonEnumClass() {
+ @SuppressWarnings("rawtypes")
+ Class rawType = Object.class;
+ @SuppressWarnings("rawtypes")
+ List rawList = new ArrayList();
+ EnumUtils.generateBitVector(rawType, rawList);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test(expected=IllegalArgumentException.class)
+ public void test_generateBitVector_nonEnumClassWithArray() {
+ @SuppressWarnings("rawtypes")
+ Class rawType = Object.class;
+ EnumUtils.generateBitVector(rawType);
+ }
+
+ @Test
+ public void test_generateBitVector() {
+ assertEquals(0L, EnumUtils.generateBitVector(Traffic.class, EnumSet.noneOf(Traffic.class)));
+ assertEquals(1L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.RED)));
+ assertEquals(2L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.AMBER)));
+ assertEquals(4L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.GREEN)));
+ assertEquals(3L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.RED, Traffic.AMBER)));
+ assertEquals(5L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.RED, Traffic.GREEN)));
+ assertEquals(6L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.AMBER, Traffic.GREEN)));
+ assertEquals(7L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.RED, Traffic.AMBER, Traffic.GREEN)));
+ }
+
+ @Test
+ public void test_generateBitVectorFromArray() {
+ assertEquals(0L, EnumUtils.generateBitVector(Traffic.class));
+ assertEquals(1L, EnumUtils.generateBitVector(Traffic.class, Traffic.RED));
+ assertEquals(2L, EnumUtils.generateBitVector(Traffic.class, Traffic.AMBER));
+ assertEquals(4L, EnumUtils.generateBitVector(Traffic.class, Traffic.GREEN));
+ assertEquals(3L, EnumUtils.generateBitVector(Traffic.class, Traffic.RED, Traffic.AMBER));
+ assertEquals(5L, EnumUtils.generateBitVector(Traffic.class, Traffic.RED, Traffic.GREEN));
+ assertEquals(6L, EnumUtils.generateBitVector(Traffic.class, Traffic.AMBER, Traffic.GREEN));
+ assertEquals(7L, EnumUtils.generateBitVector(Traffic.class, Traffic.RED, Traffic.AMBER, Traffic.GREEN));
+ //gracefully handles duplicates:
+ assertEquals(7L, EnumUtils.generateBitVector(Traffic.class, Traffic.RED, Traffic.AMBER, Traffic.GREEN, Traffic.GREEN));
+ }
+
+ @Test(expected=NullPointerException.class)
+ public void test_processBitVector_nullClass() {
+ final Class empty = null;
+ EnumUtils.processBitVector(empty, 0L);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void test_processBitVector_longClass() {
+ EnumUtils.processBitVector(TooMany.class, 0L);
+ }
+
+ @Test
+ public void test_processBitVector() {
+ assertEquals(EnumSet.noneOf(Traffic.class), EnumUtils.processBitVector(Traffic.class, 0L));
+ assertEquals(EnumSet.of(Traffic.RED), EnumUtils.processBitVector(Traffic.class, 1L));
+ assertEquals(EnumSet.of(Traffic.AMBER), EnumUtils.processBitVector(Traffic.class, 2L));
+ assertEquals(EnumSet.of(Traffic.RED, Traffic.AMBER), EnumUtils.processBitVector(Traffic.class, 3L));
+ assertEquals(EnumSet.of(Traffic.GREEN), EnumUtils.processBitVector(Traffic.class, 4L));
+ assertEquals(EnumSet.of(Traffic.RED, Traffic.GREEN), EnumUtils.processBitVector(Traffic.class, 5L));
+ assertEquals(EnumSet.of(Traffic.AMBER, Traffic.GREEN), EnumUtils.processBitVector(Traffic.class, 6L));
+ assertEquals(EnumSet.of(Traffic.RED, Traffic.AMBER, Traffic.GREEN), EnumUtils.processBitVector(Traffic.class, 7L));
+ }
+}
+
+enum Traffic {
+ RED, AMBER, GREEN
+}
+
+enum TooMany {
+ A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,
+ A1,B1,C1,D1,E1,F1,G1,H1,I1,J1,K1,L1,M1,N1,O1,P1,Q1,R1,S1,T1,U1,V1,W1,X1,Y1,Z1,
+ A2,B2,C2,D2,E2,F2,G2,H2,I2,J2,K2,L2,M2;
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/JavaVersion.java b/ApacheCommonsLang/org/apache/commons/lang3/JavaVersion.java
new file mode 100644
index 0000000..4901f6d
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/JavaVersion.java
@@ -0,0 +1,168 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+package org.apache.commons.lang3;
+
+/**
+ * An enum representing all the versions of the Java specification.
+ * This is intended to mirror available values from the
+ * java.specification.version System property.
+ *
+ * @since 3.0
+ * @version $Id: $
+ */
+public enum JavaVersion {
+
+ /**
+ * The Java version reported by Android. This is not an official Java version number.
+ */
+ JAVA_0_9(1.5f, "0.9"),
+
+ /**
+ * Java 1.1.
+ */
+ JAVA_1_1(1.1f, "1.1"),
+
+ /**
+ * Java 1.2.
+ */
+ JAVA_1_2(1.2f, "1.2"),
+
+ /**
+ * Java 1.3.
+ */
+ JAVA_1_3(1.3f, "1.3"),
+
+ /**
+ * Java 1.4.
+ */
+ JAVA_1_4(1.4f, "1.4"),
+
+ /**
+ * Java 1.5.
+ */
+ JAVA_1_5(1.5f, "1.5"),
+
+ /**
+ * Java 1.6.
+ */
+ JAVA_1_6(1.6f, "1.6"),
+
+ /**
+ * Java 1.7.
+ */
+ JAVA_1_7(1.7f, "1.7"),
+
+ /**
+ * Java 1.8.
+ */
+ JAVA_1_8(1.8f, "1.8");
+
+ /**
+ * The float value.
+ */
+ private float value;
+ /**
+ * The standard name.
+ */
+ private String name;
+
+ /**
+ * Constructor.
+ *
+ * @param value the float value
+ * @param name the standard name, not null
+ */
+ JavaVersion(final float value, final String name) {
+ this.value = value;
+ this.name = name;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Whether this version of Java is at least the version of Java passed in.
+ *
+ * For example:
+ * {@code myVersion.atLeast(JavaVersion.JAVA_1_4)}
+ *
+ * @param requiredVersion the version to check against, not null
+ * @return true if this version is equal to or greater than the specified version
+ */
+ public boolean atLeast(JavaVersion requiredVersion) {
+ return this.value >= requiredVersion.value;
+ }
+
+ /**
+ * Transforms the given string with a Java version number to the
+ * corresponding constant of this enumeration class. This method is used
+ * internally.
+ *
+ * @param nom the Java version as string
+ * @return the corresponding enumeration constant or null if the
+ * version is unknown
+ */
+ // helper for static importing
+ static JavaVersion getJavaVersion(final String nom) {
+ return get(nom);
+ }
+
+ /**
+ * Transforms the given string with a Java version number to the
+ * corresponding constant of this enumeration class. This method is used
+ * internally.
+ *
+ * @param nom the Java version as string
+ * @return the corresponding enumeration constant or null if the
+ * version is unknown
+ */
+ static JavaVersion get(final String nom) {
+ if ("0.9".equals(nom)) {
+ return JAVA_0_9;
+ } else if ("1.1".equals(nom)) {
+ return JAVA_1_1;
+ } else if ("1.2".equals(nom)) {
+ return JAVA_1_2;
+ } else if ("1.3".equals(nom)) {
+ return JAVA_1_3;
+ } else if ("1.4".equals(nom)) {
+ return JAVA_1_4;
+ } else if ("1.5".equals(nom)) {
+ return JAVA_1_5;
+ } else if ("1.6".equals(nom)) {
+ return JAVA_1_6;
+ } else if ("1.7".equals(nom)) {
+ return JAVA_1_7;
+ } else if ("1.8".equals(nom)) {
+ return JAVA_1_8;
+ } else {
+ return null;
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ *
The string value is overridden to return the standard name.
+ *
+ * For example, "1.5"
.
+ *
+ * @return the name, not null
+ */
+ @Override
+ public String toString() {
+ return name;
+ }
+
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/JavaVersionTest.java b/ApacheCommonsLang/org/apache/commons/lang3/JavaVersionTest.java
new file mode 100644
index 0000000..f282fc5
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/JavaVersionTest.java
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+package org.apache.commons.lang3;
+
+import static org.apache.commons.lang3.JavaVersion.JAVA_0_9;
+import static org.apache.commons.lang3.JavaVersion.JAVA_1_1;
+import static org.apache.commons.lang3.JavaVersion.JAVA_1_2;
+import static org.apache.commons.lang3.JavaVersion.JAVA_1_3;
+import static org.apache.commons.lang3.JavaVersion.JAVA_1_4;
+import static org.apache.commons.lang3.JavaVersion.JAVA_1_5;
+import static org.apache.commons.lang3.JavaVersion.JAVA_1_6;
+import static org.apache.commons.lang3.JavaVersion.JAVA_1_7;
+import static org.apache.commons.lang3.JavaVersion.JAVA_1_8;
+import static org.apache.commons.lang3.JavaVersion.get;
+import static org.apache.commons.lang3.JavaVersion.getJavaVersion;
+import junit.framework.TestCase;
+
+/**
+ * Unit tests {@link org.apache.commons.lang3.JavaVersion}.
+ *
+ * @version $Id: JavaVersionTest.java 918366 2010-03-03 08:56:22Z bayard $
+ */
+public class JavaVersionTest extends TestCase {
+
+ public void testGetJavaVersion() {
+ assertEquals("0.9 failed", JAVA_0_9, get("0.9"));
+ assertEquals("1.1 failed", JAVA_1_1, get("1.1"));
+ assertEquals("1.2 failed", JAVA_1_2, get("1.2"));
+ assertEquals("1.3 failed", JAVA_1_3, get("1.3"));
+ assertEquals("1.4 failed", JAVA_1_4, get("1.4"));
+ assertEquals("1.5 failed", JAVA_1_5, get("1.5"));
+ assertEquals("1.6 failed", JAVA_1_6, get("1.6"));
+ assertEquals("1.7 failed", JAVA_1_7, get("1.7"));
+ assertEquals("1.8 failed", JAVA_1_8, get("1.8"));
+ assertNull("1.9 unexpectedly worked", get("1.9"));
+ assertEquals("Wrapper method failed", get("1.5"), getJavaVersion("1.5"));
+ }
+
+ public void testAtLeast() {
+ assertFalse("1.2 at least 1.5 passed", JAVA_1_2.atLeast(JAVA_1_5));
+ assertTrue("1.5 at least 1.2 failed", JAVA_1_5.atLeast(JAVA_1_2));
+ assertFalse("1.6 at least 1.7 passed", JAVA_1_6.atLeast(JAVA_1_7));
+
+ assertTrue("0.9 at least 1.5 failed", JAVA_0_9.atLeast(JAVA_1_5));
+ assertFalse("0.9 at least 1.6 passed", JAVA_0_9.atLeast(JAVA_1_6));
+ }
+
+ public void testToString() {
+ assertEquals("1.2", JAVA_1_2.toString());
+ }
+
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/LocaleUtils.java b/ApacheCommonsLang/org/apache/commons/lang3/LocaleUtils.java
new file mode 100644
index 0000000..a280f46
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/LocaleUtils.java
@@ -0,0 +1,297 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+package org.apache.commons.lang3;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+/**
+ * Operations to assist when working with a {@link Locale}.
+ *
+ * This class tries to handle {@code null} input gracefully.
+ * An exception will not be thrown for a {@code null} input.
+ * Each method documents its behaviour in more detail.
+ *
+ * @since 2.2
+ * @version $Id: LocaleUtils.java 1342651 2012-05-25 14:39:38Z sebb $
+ */
+public class LocaleUtils {
+
+ /** Concurrent map of language locales by country. */
+ private static final ConcurrentMap> cLanguagesByCountry =
+ new ConcurrentHashMap>();
+
+ /** Concurrent map of country locales by language. */
+ private static final ConcurrentMap> cCountriesByLanguage =
+ new ConcurrentHashMap>();
+
+ /**
+ * {@code LocaleUtils} instances should NOT be constructed in standard programming.
+ * Instead, the class should be used as {@code LocaleUtils.toLocale("en_GB");}.
+ *
+ * This constructor is public to permit tools that require a JavaBean instance
+ * to operate.
+ */
+ public LocaleUtils() {
+ super();
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Converts a String to a Locale.
+ *
+ * This method takes the string format of a locale and creates the
+ * locale object from it.
+ *
+ *
+ * LocaleUtils.toLocale("en") = new Locale("en", "")
+ * LocaleUtils.toLocale("en_GB") = new Locale("en", "GB")
+ * LocaleUtils.toLocale("en_GB_xxx") = new Locale("en", "GB", "xxx") (#)
+ *
+ *
+ * (#) The behaviour of the JDK variant constructor changed between JDK1.3 and JDK1.4.
+ * In JDK1.3, the constructor upper cases the variant, in JDK1.4, it doesn't.
+ * Thus, the result from getVariant() may vary depending on your JDK.
+ *
+ * This method validates the input strictly.
+ * The language code must be lowercase.
+ * The country code must be uppercase.
+ * The separator must be an underscore.
+ * The length must be correct.
+ *
+ *
+ * @param str the locale String to convert, null returns null
+ * @return a Locale, null if null input
+ * @throws IllegalArgumentException if the string is an invalid format
+ */
+ public static Locale toLocale(String str) {
+ if (str == null) {
+ return null;
+ }
+ int len = str.length();
+ if (len != 2 && len != 5 && len < 7) {
+ throw new IllegalArgumentException("Invalid locale format: " + str);
+ }
+ char ch0 = str.charAt(0);
+ char ch1 = str.charAt(1);
+ if (ch0 < 'a' || ch0 > 'z' || ch1 < 'a' || ch1 > 'z') {
+ throw new IllegalArgumentException("Invalid locale format: " + str);
+ }
+ if (len == 2) {
+ return new Locale(str, "");
+ } else {
+ if (str.charAt(2) != '_') {
+ throw new IllegalArgumentException("Invalid locale format: " + str);
+ }
+ char ch3 = str.charAt(3);
+ if (ch3 == '_') {
+ return new Locale(str.substring(0, 2), "", str.substring(4));
+ }
+ char ch4 = str.charAt(4);
+ if (ch3 < 'A' || ch3 > 'Z' || ch4 < 'A' || ch4 > 'Z') {
+ throw new IllegalArgumentException("Invalid locale format: " + str);
+ }
+ if (len == 5) {
+ return new Locale(str.substring(0, 2), str.substring(3, 5));
+ } else {
+ if (str.charAt(5) != '_') {
+ throw new IllegalArgumentException("Invalid locale format: " + str);
+ }
+ return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6));
+ }
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Obtains the list of locales to search through when performing
+ * a locale search.
+ *
+ *
+ * localeLookupList(Locale("fr","CA","xxx"))
+ * = [Locale("fr","CA","xxx"), Locale("fr","CA"), Locale("fr")]
+ *
+ *
+ * @param locale the locale to start from
+ * @return the unmodifiable list of Locale objects, 0 being locale, not null
+ */
+ public static List localeLookupList(Locale locale) {
+ return localeLookupList(locale, locale);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Obtains the list of locales to search through when performing
+ * a locale search.
+ *
+ *
+ * localeLookupList(Locale("fr", "CA", "xxx"), Locale("en"))
+ * = [Locale("fr","CA","xxx"), Locale("fr","CA"), Locale("fr"), Locale("en"]
+ *
+ *
+ * The result list begins with the most specific locale, then the
+ * next more general and so on, finishing with the default locale.
+ * The list will never contain the same locale twice.
+ *
+ * @param locale the locale to start from, null returns empty list
+ * @param defaultLocale the default locale to use if no other is found
+ * @return the unmodifiable list of Locale objects, 0 being locale, not null
+ */
+ public static List localeLookupList(Locale locale, Locale defaultLocale) {
+ List list = new ArrayList(4);
+ if (locale != null) {
+ list.add(locale);
+ if (locale.getVariant().length() > 0) {
+ list.add(new Locale(locale.getLanguage(), locale.getCountry()));
+ }
+ if (locale.getCountry().length() > 0) {
+ list.add(new Locale(locale.getLanguage(), ""));
+ }
+ if (list.contains(defaultLocale) == false) {
+ list.add(defaultLocale);
+ }
+ }
+ return Collections.unmodifiableList(list);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Obtains an unmodifiable list of installed locales.
+ *
+ * This method is a wrapper around {@link Locale#getAvailableLocales()}.
+ * It is more efficient, as the JDK method must create a new array each
+ * time it is called.
+ *
+ * @return the unmodifiable list of available locales
+ */
+ public static List availableLocaleList() {
+ return SyncAvoid.AVAILABLE_LOCALE_LIST;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Obtains an unmodifiable set of installed locales.
+ *
+ * This method is a wrapper around {@link Locale#getAvailableLocales()}.
+ * It is more efficient, as the JDK method must create a new array each
+ * time it is called.
+ *
+ * @return the unmodifiable set of available locales
+ */
+ public static Set availableLocaleSet() {
+ return SyncAvoid.AVAILABLE_LOCALE_SET;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Checks if the locale specified is in the list of available locales.
+ *
+ * @param locale the Locale object to check if it is available
+ * @return true if the locale is a known locale
+ */
+ public static boolean isAvailableLocale(Locale locale) {
+ return availableLocaleList().contains(locale);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Obtains the list of languages supported for a given country.
+ *
+ * This method takes a country code and searches to find the
+ * languages available for that country. Variant locales are removed.
+ *
+ * @param countryCode the 2 letter country code, null returns empty
+ * @return an unmodifiable List of Locale objects, not null
+ */
+ public static List languagesByCountry(String countryCode) {
+ if (countryCode == null) {
+ return Collections.emptyList();
+ }
+ List langs = cLanguagesByCountry.get(countryCode);
+ if (langs == null) {
+ langs = new ArrayList();
+ List locales = availableLocaleList();
+ for (int i = 0; i < locales.size(); i++) {
+ Locale locale = locales.get(i);
+ if (countryCode.equals(locale.getCountry()) &&
+ locale.getVariant().isEmpty()) {
+ langs.add(locale);
+ }
+ }
+ langs = Collections.unmodifiableList(langs);
+ cLanguagesByCountry.putIfAbsent(countryCode, langs);
+ langs = cLanguagesByCountry.get(countryCode);
+ }
+ return langs;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Obtains the list of countries supported for a given language.
+ *
+ * This method takes a language code and searches to find the
+ * countries available for that language. Variant locales are removed.
+ *
+ * @param languageCode the 2 letter language code, null returns empty
+ * @return an unmodifiable List of Locale objects, not null
+ */
+ public static List countriesByLanguage(String languageCode) {
+ if (languageCode == null) {
+ return Collections.emptyList();
+ }
+ List countries = cCountriesByLanguage.get(languageCode);
+ if (countries == null) {
+ countries = new ArrayList();
+ List locales = availableLocaleList();
+ for (int i = 0; i < locales.size(); i++) {
+ Locale locale = locales.get(i);
+ if (languageCode.equals(locale.getLanguage()) &&
+ locale.getCountry().length() != 0 &&
+ locale.getVariant().isEmpty()) {
+ countries.add(locale);
+ }
+ }
+ countries = Collections.unmodifiableList(countries);
+ cCountriesByLanguage.putIfAbsent(languageCode, countries);
+ countries = cCountriesByLanguage.get(languageCode);
+ }
+ return countries;
+ }
+
+ //-----------------------------------------------------------------------
+ // class to avoid synchronization (Init on demand)
+ static class SyncAvoid {
+ /** Unmodifiable list of available locales. */
+ private static final List AVAILABLE_LOCALE_LIST;
+ /** Unmodifiable set of available locales. */
+ private static final Set AVAILABLE_LOCALE_SET;
+
+ static {
+ List list = new ArrayList(Arrays.asList(Locale.getAvailableLocales())); // extra safe
+ AVAILABLE_LOCALE_LIST = Collections.unmodifiableList(list);
+ AVAILABLE_LOCALE_SET = Collections.unmodifiableSet(new HashSet(list));
+ }
+ }
+
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/LocaleUtilsTest.java b/ApacheCommonsLang/org/apache/commons/lang3/LocaleUtilsTest.java
new file mode 100644
index 0000000..51afb59
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/LocaleUtilsTest.java
@@ -0,0 +1,488 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+package org.apache.commons.lang3;
+
+import static org.apache.commons.lang3.JavaVersion.JAVA_1_4;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Modifier;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+
+import junit.framework.TestCase;
+
+/**
+ * Unit tests for {@link LocaleUtils}.
+ *
+ * @version $Id: LocaleUtilsTest.java 1299411 2012-03-11 17:55:29Z ggregory $
+ */
+public class LocaleUtilsTest extends TestCase {
+
+ private static final Locale LOCALE_EN = new Locale("en", "");
+ private static final Locale LOCALE_EN_US = new Locale("en", "US");
+ private static final Locale LOCALE_EN_US_ZZZZ = new Locale("en", "US", "ZZZZ");
+ private static final Locale LOCALE_FR = new Locale("fr", "");
+ private static final Locale LOCALE_FR_CA = new Locale("fr", "CA");
+ private static final Locale LOCALE_QQ = new Locale("qq", "");
+ private static final Locale LOCALE_QQ_ZZ = new Locale("qq", "ZZ");
+
+ /**
+ * Constructor.
+ *
+ * @param name
+ */
+ public LocaleUtilsTest(String name) {
+ super(name);
+ }
+
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+
+ // Testing #LANG-304. Must be called before availableLocaleSet is called.
+ LocaleUtils.isAvailableLocale(Locale.getDefault());
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Test that constructors are public, and work, etc.
+ */
+ public void testConstructor() {
+ assertNotNull(new LocaleUtils());
+ Constructor>[] cons = LocaleUtils.class.getDeclaredConstructors();
+ assertEquals(1, cons.length);
+ assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
+ assertEquals(true, Modifier.isPublic(LocaleUtils.class.getModifiers()));
+ assertEquals(false, Modifier.isFinal(LocaleUtils.class.getModifiers()));
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Pass in a valid language, test toLocale.
+ *
+ * @param language the language string
+ */
+ private void assertValidToLocale(String language) {
+ Locale locale = LocaleUtils.toLocale(language);
+ assertNotNull("valid locale", locale);
+ assertEquals(language, locale.getLanguage());
+ //country and variant are empty
+ assertTrue(locale.getCountry() == null || locale.getCountry().isEmpty());
+ assertTrue(locale.getVariant() == null || locale.getVariant().isEmpty());
+ }
+
+ /**
+ * Pass in a valid language, test toLocale.
+ *
+ * @param localeString to pass to toLocale()
+ * @param language of the resulting Locale
+ * @param country of the resulting Locale
+ */
+ private void assertValidToLocale(String localeString, String language, String country) {
+ Locale locale = LocaleUtils.toLocale(localeString);
+ assertNotNull("valid locale", locale);
+ assertEquals(language, locale.getLanguage());
+ assertEquals(country, locale.getCountry());
+ //variant is empty
+ assertTrue(locale.getVariant() == null || locale.getVariant().isEmpty());
+ }
+
+ /**
+ * Pass in a valid language, test toLocale.
+ *
+ * @param localeString to pass to toLocale()
+ * @param language of the resulting Locale
+ * @param country of the resulting Locale
+ * @param variant of the resulting Locale
+ */
+ private void assertValidToLocale(
+ String localeString, String language,
+ String country, String variant) {
+ Locale locale = LocaleUtils.toLocale(localeString);
+ assertNotNull("valid locale", locale);
+ assertEquals(language, locale.getLanguage());
+ assertEquals(country, locale.getCountry());
+ assertEquals(variant, locale.getVariant());
+
+ }
+
+ /**
+ * Test toLocale() method.
+ */
+ public void testToLocale_1Part() {
+ assertEquals(null, LocaleUtils.toLocale((String) null));
+
+ assertValidToLocale("us");
+ assertValidToLocale("fr");
+ assertValidToLocale("de");
+ assertValidToLocale("zh");
+ // Valid format but lang doesnt exist, should make instance anyway
+ assertValidToLocale("qq");
+
+ try {
+ LocaleUtils.toLocale("Us");
+ fail("Should fail if not lowercase");
+ } catch (IllegalArgumentException iae) {}
+ try {
+ LocaleUtils.toLocale("US");
+ fail("Should fail if not lowercase");
+ } catch (IllegalArgumentException iae) {}
+ try {
+ LocaleUtils.toLocale("uS");
+ fail("Should fail if not lowercase");
+ } catch (IllegalArgumentException iae) {}
+ try {
+ LocaleUtils.toLocale("u#");
+ fail("Should fail if not lowercase");
+ } catch (IllegalArgumentException iae) {}
+
+ try {
+ LocaleUtils.toLocale("u");
+ fail("Must be 2 chars if less than 5");
+ } catch (IllegalArgumentException iae) {}
+
+ try {
+ LocaleUtils.toLocale("uuu");
+ fail("Must be 2 chars if less than 5");
+ } catch (IllegalArgumentException iae) {}
+
+ try {
+ LocaleUtils.toLocale("uu_U");
+ fail("Must be 2 chars if less than 5");
+ } catch (IllegalArgumentException iae) {}
+ }
+
+ /**
+ * Test toLocale() method.
+ */
+ public void testToLocale_2Part() {
+ assertValidToLocale("us_EN", "us", "EN");
+ //valid though doesnt exist
+ assertValidToLocale("us_ZH", "us", "ZH");
+
+ try {
+ LocaleUtils.toLocale("us-EN");
+ fail("Should fail as not underscore");
+ } catch (IllegalArgumentException iae) {}
+ try {
+ LocaleUtils.toLocale("us_En");
+ fail("Should fail second part not uppercase");
+ } catch (IllegalArgumentException iae) {}
+ try {
+ LocaleUtils.toLocale("us_en");
+ fail("Should fail second part not uppercase");
+ } catch (IllegalArgumentException iae) {}
+ try {
+ LocaleUtils.toLocale("us_eN");
+ fail("Should fail second part not uppercase");
+ } catch (IllegalArgumentException iae) {}
+ try {
+ LocaleUtils.toLocale("uS_EN");
+ fail("Should fail first part not lowercase");
+ } catch (IllegalArgumentException iae) {}
+ try {
+ LocaleUtils.toLocale("us_E3");
+ fail("Should fail second part not uppercase");
+ } catch (IllegalArgumentException iae) {}
+ }
+
+ /**
+ * Test toLocale() method.
+ */
+ public void testToLocale_3Part() {
+ assertValidToLocale("us_EN_A", "us", "EN", "A");
+ // this isn't pretty, but was caused by a jdk bug it seems
+ // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4210525
+ if (SystemUtils.isJavaVersionAtLeast(JAVA_1_4)) {
+ assertValidToLocale("us_EN_a", "us", "EN", "a");
+ assertValidToLocale("us_EN_SFsafdFDsdfF", "us", "EN", "SFsafdFDsdfF");
+ } else {
+ assertValidToLocale("us_EN_a", "us", "EN", "A");
+ assertValidToLocale("us_EN_SFsafdFDsdfF", "us", "EN", "SFSAFDFDSDFF");
+ }
+
+ try {
+ LocaleUtils.toLocale("us_EN-a");
+ fail("Should fail as not underscore");
+ } catch (IllegalArgumentException iae) {}
+ try {
+ LocaleUtils.toLocale("uu_UU_");
+ fail("Must be 3, 5 or 7+ in length");
+ } catch (IllegalArgumentException iae) {}
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Helper method for local lookups.
+ *
+ * @param locale the input locale
+ * @param defaultLocale the input default locale
+ * @param expected expected results
+ */
+ private void assertLocaleLookupList(Locale locale, Locale defaultLocale, Locale[] expected) {
+ List localeList = defaultLocale == null ?
+ LocaleUtils.localeLookupList(locale) :
+ LocaleUtils.localeLookupList(locale, defaultLocale);
+
+ assertEquals(expected.length, localeList.size());
+ assertEquals(Arrays.asList(expected), localeList);
+ assertUnmodifiableCollection(localeList);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Test localeLookupList() method.
+ */
+ public void testLocaleLookupList_Locale() {
+ assertLocaleLookupList(null, null, new Locale[0]);
+ assertLocaleLookupList(LOCALE_QQ, null, new Locale[]{LOCALE_QQ});
+ assertLocaleLookupList(LOCALE_EN, null, new Locale[]{LOCALE_EN});
+ assertLocaleLookupList(LOCALE_EN, null, new Locale[]{LOCALE_EN});
+ assertLocaleLookupList(LOCALE_EN_US, null,
+ new Locale[] {
+ LOCALE_EN_US,
+ LOCALE_EN});
+ assertLocaleLookupList(LOCALE_EN_US_ZZZZ, null,
+ new Locale[] {
+ LOCALE_EN_US_ZZZZ,
+ LOCALE_EN_US,
+ LOCALE_EN});
+ }
+
+ /**
+ * Test localeLookupList() method.
+ */
+ public void testLocaleLookupList_LocaleLocale() {
+ assertLocaleLookupList(LOCALE_QQ, LOCALE_QQ,
+ new Locale[]{LOCALE_QQ});
+ assertLocaleLookupList(LOCALE_EN, LOCALE_EN,
+ new Locale[]{LOCALE_EN});
+
+ assertLocaleLookupList(LOCALE_EN_US, LOCALE_EN_US,
+ new Locale[]{
+ LOCALE_EN_US,
+ LOCALE_EN});
+ assertLocaleLookupList(LOCALE_EN_US, LOCALE_QQ,
+ new Locale[] {
+ LOCALE_EN_US,
+ LOCALE_EN,
+ LOCALE_QQ});
+ assertLocaleLookupList(LOCALE_EN_US, LOCALE_QQ_ZZ,
+ new Locale[] {
+ LOCALE_EN_US,
+ LOCALE_EN,
+ LOCALE_QQ_ZZ});
+
+ assertLocaleLookupList(LOCALE_EN_US_ZZZZ, null,
+ new Locale[] {
+ LOCALE_EN_US_ZZZZ,
+ LOCALE_EN_US,
+ LOCALE_EN});
+ assertLocaleLookupList(LOCALE_EN_US_ZZZZ, LOCALE_EN_US_ZZZZ,
+ new Locale[] {
+ LOCALE_EN_US_ZZZZ,
+ LOCALE_EN_US,
+ LOCALE_EN});
+ assertLocaleLookupList(LOCALE_EN_US_ZZZZ, LOCALE_QQ,
+ new Locale[] {
+ LOCALE_EN_US_ZZZZ,
+ LOCALE_EN_US,
+ LOCALE_EN,
+ LOCALE_QQ});
+ assertLocaleLookupList(LOCALE_EN_US_ZZZZ, LOCALE_QQ_ZZ,
+ new Locale[] {
+ LOCALE_EN_US_ZZZZ,
+ LOCALE_EN_US,
+ LOCALE_EN,
+ LOCALE_QQ_ZZ});
+ assertLocaleLookupList(LOCALE_FR_CA, LOCALE_EN,
+ new Locale[] {
+ LOCALE_FR_CA,
+ LOCALE_FR,
+ LOCALE_EN});
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Test availableLocaleList() method.
+ */
+ public void testAvailableLocaleList() {
+ List list = LocaleUtils.availableLocaleList();
+ List list2 = LocaleUtils.availableLocaleList();
+ assertNotNull(list);
+ assertSame(list, list2);
+ assertUnmodifiableCollection(list);
+
+ Locale[] jdkLocaleArray = Locale.getAvailableLocales();
+ List jdkLocaleList = Arrays.asList(jdkLocaleArray);
+ assertEquals(jdkLocaleList, list);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Test availableLocaleSet() method.
+ */
+ public void testAvailableLocaleSet() {
+ Set set = LocaleUtils.availableLocaleSet();
+ Set set2 = LocaleUtils.availableLocaleSet();
+ assertNotNull(set);
+ assertSame(set, set2);
+ assertUnmodifiableCollection(set);
+
+ Locale[] jdkLocaleArray = Locale.getAvailableLocales();
+ List jdkLocaleList = Arrays.asList(jdkLocaleArray);
+ Set jdkLocaleSet = new HashSet(jdkLocaleList);
+ assertEquals(jdkLocaleSet, set);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Test availableLocaleSet() method.
+ */
+ public void testIsAvailableLocale() {
+ Set set = LocaleUtils.availableLocaleSet();
+ assertEquals(set.contains(LOCALE_EN), LocaleUtils.isAvailableLocale(LOCALE_EN));
+ assertEquals(set.contains(LOCALE_EN_US), LocaleUtils.isAvailableLocale(LOCALE_EN_US));
+ assertEquals(set.contains(LOCALE_EN_US_ZZZZ), LocaleUtils.isAvailableLocale(LOCALE_EN_US_ZZZZ));
+ assertEquals(set.contains(LOCALE_FR), LocaleUtils.isAvailableLocale(LOCALE_FR));
+ assertEquals(set.contains(LOCALE_FR_CA), LocaleUtils.isAvailableLocale(LOCALE_FR_CA));
+ assertEquals(set.contains(LOCALE_QQ), LocaleUtils.isAvailableLocale(LOCALE_QQ));
+ assertEquals(set.contains(LOCALE_QQ_ZZ), LocaleUtils.isAvailableLocale(LOCALE_QQ_ZZ));
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Make sure the language by country is correct. It checks that
+ * the LocaleUtils.languagesByCountry(country) call contains the
+ * array of languages passed in. It may contain more due to JVM
+ * variations.
+ *
+ * @param country
+ * @param languages array of languages that should be returned
+ */
+ private void assertLanguageByCountry(String country, String[] languages) {
+ List list = LocaleUtils.languagesByCountry(country);
+ List list2 = LocaleUtils.languagesByCountry(country);
+ assertNotNull(list);
+ assertSame(list, list2);
+ //search through langauges
+ for (String language : languages) {
+ Iterator iterator = list.iterator();
+ boolean found = false;
+ // see if it was returned by the set
+ while (iterator.hasNext()) {
+ Locale locale = iterator.next();
+ // should have an en empty variant
+ assertTrue(locale.getVariant() == null
+ || locale.getVariant().isEmpty());
+ assertEquals(country, locale.getCountry());
+ if (language.equals(locale.getLanguage())) {
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ fail("Cound not find language: " + language
+ + " for country: " + country);
+ }
+ }
+ assertUnmodifiableCollection(list);
+ }
+
+ /**
+ * Test languagesByCountry() method.
+ */
+ public void testLanguagesByCountry() {
+ assertLanguageByCountry(null, new String[0]);
+ assertLanguageByCountry("GB", new String[]{"en"});
+ assertLanguageByCountry("ZZ", new String[0]);
+ assertLanguageByCountry("CH", new String[]{"fr", "de", "it"});
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Make sure the country by language is correct. It checks that
+ * the LocaleUtils.countryByLanguage(language) call contains the
+ * array of countries passed in. It may contain more due to JVM
+ * variations.
+ *
+ *
+ * @param language
+ * @param countries array of countries that should be returned
+ */
+ private void assertCountriesByLanguage(String language, String[] countries) {
+ List list = LocaleUtils.countriesByLanguage(language);
+ List list2 = LocaleUtils.countriesByLanguage(language);
+ assertNotNull(list);
+ assertSame(list, list2);
+ //search through langauges
+ for (String countrie : countries) {
+ Iterator iterator = list.iterator();
+ boolean found = false;
+ // see if it was returned by the set
+ while (iterator.hasNext()) {
+ Locale locale = iterator.next();
+ // should have an en empty variant
+ assertTrue(locale.getVariant() == null
+ || locale.getVariant().isEmpty());
+ assertEquals(language, locale.getLanguage());
+ if (countrie.equals(locale.getCountry())) {
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ fail("Cound not find language: " + countrie
+ + " for country: " + language);
+ }
+ }
+ assertUnmodifiableCollection(list);
+ }
+
+ /**
+ * Test countriesByLanguage() method.
+ */
+ public void testCountriesByLanguage() {
+ assertCountriesByLanguage(null, new String[0]);
+ assertCountriesByLanguage("de", new String[]{"DE", "CH", "AT", "LU"});
+ assertCountriesByLanguage("zz", new String[0]);
+ assertCountriesByLanguage("it", new String[]{"IT", "CH"});
+ }
+
+ /**
+ * @param coll the collection to check
+ */
+ private static void assertUnmodifiableCollection(Collection> coll) {
+ try {
+ coll.add(null);
+ fail();
+ } catch (UnsupportedOperationException ex) {}
+ }
+
+ /**
+ * Tests #LANG-328 - only language+variant
+ */
+ public void testLang328() {
+ assertValidToLocale("fr__POSIX", "fr", "", "POSIX");
+ }
+
+}
diff --git a/ApacheCommonsLang/org/apache/commons/lang3/ObjectUtils.java b/ApacheCommonsLang/org/apache/commons/lang3/ObjectUtils.java
new file mode 100644
index 0000000..2343d95
--- /dev/null
+++ b/ApacheCommonsLang/org/apache/commons/lang3/ObjectUtils.java
@@ -0,0 +1,608 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+package org.apache.commons.lang3;
+
+import java.io.Serializable;
+import java.lang.reflect.Array;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.TreeSet;
+
+import org.apache.commons.lang3.exception.CloneFailedException;
+import org.apache.commons.lang3.mutable.MutableInt;
+
+/**
+ * Operations on {@code Object}.
+ *
+ * This class tries to handle {@code null} input gracefully.
+ * An exception will generally not be thrown for a {@code null} input.
+ * Each method documents its behaviour in more detail.
+ *
+ * #ThreadSafe#
+ * @since 1.0
+ * @version $Id: ObjectUtils.java 1199894 2011-11-09 17:53:59Z ggregory $
+ */
+//@Immutable
+public class ObjectUtils {
+
+ /**
+ * Singleton used as a {@code null} placeholder where
+ * {@code null} has another meaning.
+ *
+ * For example, in a {@code HashMap} the
+ * {@link java.util.HashMap#get(java.lang.Object)} method returns
+ * {@code null} if the {@code Map} contains {@code null} or if there
+ * is no matching key. The {@code Null} placeholder can be used to
+ * distinguish between these two cases.
+ *
+ * Another example is {@code Hashtable}, where {@code null}
+ * cannot be stored.
+ *
+ * This instance is Serializable.
+ */
+ public static final Null NULL = new Null();
+
+ /**
+ * {@code ObjectUtils} instances should NOT be constructed in
+ * standard programming. Instead, the static methods on the class should
+ * be used, such as {@code ObjectUtils.defaultIfNull("a","b");}.
+ *
+ * This constructor is public to permit tools that require a JavaBean
+ * instance to operate.
+ */
+ public ObjectUtils() {
+ super();
+ }
+
+ // Defaulting
+ //-----------------------------------------------------------------------
+ /**
+ * Returns a default value if the object passed is {@code null}.
+ *
+ *
+ * ObjectUtils.defaultIfNull(null, null) = null
+ * ObjectUtils.defaultIfNull(null, "") = ""
+ * ObjectUtils.defaultIfNull(null, "zz") = "zz"
+ * ObjectUtils.defaultIfNull("abc", *) = "abc"
+ * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
+ *
+ *
+ * @param the type of the object
+ * @param object the {@code Object} to test, may be {@code null}
+ * @param defaultValue the default value to return, may be {@code null}
+ * @return {@code object} if it is not {@code null}, defaultValue otherwise
+ */
+ public static T defaultIfNull(T object, T defaultValue) {
+ return object != null ? object : defaultValue;
+ }
+
+ /**
+ * Returns the first value in the array which is not {@code null}.
+ * If all the values are {@code null} or the array is {@code null}
+ * or empty then {@code null} is returned.
+ *
+ *
+ * ObjectUtils.firstNonNull(null, null) = null
+ * ObjectUtils.firstNonNull(null, "") = ""
+ * ObjectUtils.firstNonNull(null, null, "") = ""
+ * ObjectUtils.firstNonNull(null, "zz") = "zz"
+ * ObjectUtils.firstNonNull("abc", *) = "abc"
+ * ObjectUtils.firstNonNull(null, "xyz", *) = "xyz"
+ * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
+ * ObjectUtils.firstNonNull() = null
+ *
+ *
+ * @param the component type of the array
+ * @param values the values to test, may be {@code null} or empty
+ * @return the first value from {@code values} which is not {@code null},
+ * or {@code null} if there are no non-null values
+ * @since 3.0
+ */
+ public static