一、前言
关于glassfish的grizzly-core源码包中的org.glassfish.grizzly.utils.ArrayUtils数组工具类,对数组二进制搜索binarySearch、添加不重复元素addUnique、数组元素删除及查找元素序号等方法等操作。
二、源码说明
package org.glassfish.grizzly.utils;@b@@b@import java.lang.reflect.Array;@b@import java.util.Arrays;@b@@b@public final class ArrayUtils@b@{@b@ public static int binarySearch(int[] a, int fromIndex, int toIndex, int key)@b@ {@b@ int low = fromIndex;@b@ int high = toIndex - 1;@b@@b@ while (low <= high) {@b@ int mid = low + high >>> 1;@b@ int midVal = a[mid];@b@@b@ if (midVal < key)@b@ low = mid + 1;@b@ else if (midVal > key)@b@ high = mid - 1;@b@ else@b@ return mid;@b@ }@b@ return low;@b@ }@b@@b@ public static <T> T[] addUnique(T[] array, T element)@b@ {@b@ return addUnique(array, element, true);@b@ }@b@@b@ public static <T> T[] addUnique(T[] array, T element, boolean replaceElementIfEquals)@b@ {@b@ int idx = indexOf(array, element);@b@ if (idx == -1) {@b@ int length = array.length;@b@ Object[] newArray = Arrays.copyOf(array, length + 1);@b@ newArray[length] = element;@b@ return newArray;@b@ }@b@@b@ if (replaceElementIfEquals) {@b@ array[idx] = element;@b@ }@b@@b@ return array;@b@ }@b@@b@ public static <T> T[] remove(T[] array, Object element)@b@ {@b@ int idx = indexOf(array, element);@b@ if (idx != -1) {@b@ int length = array.length;@b@@b@ if (length == 1) {@b@ return null;@b@ }@b@@b@ Object[] newArray = (Object[])(Object[])Array.newInstance(array.getClass().getComponentType(), length - 1);@b@@b@ if (idx > 0) {@b@ System.arraycopy(array, 0, newArray, 0, idx);@b@ }@b@@b@ if (idx < length - 1) {@b@ System.arraycopy(array, idx + 1, newArray, idx, length - idx - 1);@b@ }@b@@b@ return newArray;@b@ }@b@@b@ return array;@b@ }@b@@b@ public static <T> int indexOf(T[] array, Object element)@b@ {@b@ for (int i = 0; i < array.length; ++i) {@b@ if (element.equals(array[i]))@b@ return i;@b@@b@ }@b@@b@ return -1;@b@ }@b@}