package cn.cd.sg.array.utils;
import java.lang.reflect.Array;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import cn.cd.sg.validate.utils.Validate;
@SuppressWarnings("unchecked")
public class ArrayUtils {
public static final Object EMPTY_OBJECT_ARRAY[] = new Object[0];
public static final Class EMPTY_CLASS_ARRAY[] = new Class[0];
public static final String EMPTY_STRING_ARRAY[] = new String[0];
public static final long EMPTY_LONG_ARRAY[] = new long[0];
public static final Long EMPTY_LONG_OBJECT_ARRAY[] = new Long[0];
public static final int EMPTY_INT_ARRAY[] = new int[0];
public static final Integer EMPTY_INTEGER_OBJECT_ARRAY[] = new Integer[0];
public static final short EMPTY_SHORT_ARRAY[] = new short[0];
public static final Short EMPTY_SHORT_OBJECT_ARRAY[] = new Short[0];
public static final byte EMPTY_BYTE_ARRAY[] = new byte[0];
public static final Byte EMPTY_BYTE_OBJECT_ARRAY[] = new Byte[0];
public static final double EMPTY_DOUBLE_ARRAY[] = new double[0];
public static final Double EMPTY_DOUBLE_OBJECT_ARRAY[] = new Double[0];
public static final float EMPTY_FLOAT_ARRAY[] = new float[0];
public static final Float EMPTY_FLOAT_OBJECT_ARRAY[] = new Float[0];
public static final boolean EMPTY_BOOLEAN_ARRAY[] = new boolean[0];
public static final Boolean EMPTY_BOOLEAN_OBJECT_ARRAY[] = new Boolean[0];
public static final char EMPTY_CHAR_ARRAY[] = new char[0];
public static final Character EMPTY_CHARACTER_OBJECT_ARRAY[] = new Character[0];
public static final int INDEX_NOT_FOUND = -1;
/**
* 描述 : ()
* 方法名: toString
* 创建人:孙刚
* 创建时间:2014-1-22 上午10:41:23
* @param array
* @return :String
*/
public static String toString(Object array) {
return toString(array, "{}");
}
/**
* 描述 : (打印数组)
* 方法名: toString
* 创建人:孙刚
* 创建时间:2014-1-22 上午10:41:41
* @param array
* @param stringIfNull
* @return :String
*/
public static String toString(Object array, String stringIfNull) {
if (array == null) {
return stringIfNull;
} else {
return (new ToStringBuilder(array, ToStringStyle.SIMPLE_STYLE))
.append(array).toString();
}
}
/**
* 描述 : ()
* 方法名: hashCode
* 创建人:孙刚
* 创建时间:2014-1-22 上午10:42:37
*
* @param array
* @return :int
*/
public static int hashCode(Object array) {
return (new HashCodeBuilder()).append(array).toHashCode();
}
/**
* 描述 : (判断数组内容是否相等)
* 方法名: isEquals
* 创建人:孙刚
* 创建时间:2014-1-22 上午10:43:19
* @param array1
* @param array2
* @return :boolean
*/
public static boolean isEquals(Object array1, Object array2) {
return (new EqualsBuilder()).append(array1, array2).isEquals();
}
/**
* 描述 : ()
* 方法名: toMap
* 创建人:孙刚
* 创建时间:2014-1-22 上午10:43:44
* @param array
* @return :Map
*/
public static Map toMap(Object array[]) {
Validate.notNull(array, "array is not null");
Map map = new HashMap((int) ((double) array.length * 1.5D));
for (int i = 0; i < array.length; i++) {
Object object = array[i];
if (object instanceof Entry) {
Entry entry = (Entry) object;
map.put(entry.getKey(), entry.getValue());
continue;
}
if (object instanceof Object[]) {
Object entry[] = (Object[]) (Object[]) object;
if (entry.length < 2) {
throw new IllegalArgumentException("Array element " + i
+ ", '" + object + "', has a length less than 2");
}
map.put(entry[0], entry[1]);
} else {
throw new IllegalArgumentException("Array element " + i + ", '"
+ object
+ "', is neither of type Map.Entry nor an Array");
}
}
return map;
}
/**
* 描述 : (复制)
* 方法名: clone
* 创建人:孙刚
* 创建时间:2014-1-22 上午10:48:01
* @param array
* @return :Object[]
*/
public static Object[] clone(Object array[]) {
if (array == null) {
return null;
} else {
return (Object[]) (Object[]) array.clone();
}
}
public static long[] clone(long array[]) {
if (array == null) {
return null;
} else {
return (long[]) (long[]) array.clone();
}
}
public static int[] clone(int array[]) {
if (array == null) {
return null;
} else {
return (int[]) (int[]) array.clone();
}
}
public static short[] clone(short array[]) {
if (array == null) {
return null;
} else {
return (short[]) (short[]) array.clone();
}
}
public static char[] clone(char array[]) {
if (array == null) {
return null;
} else {
return (char[]) (char[]) array.clone();
}
}
public static byte[] clone(byte array[]) {
if (array == null) {
return null;
} else {
return (byte[]) (byte[]) array.clone();
}
}
public static double[] clone(double array[]) {
if (array == null) {
return null;
} else {
return (double[]) (double[]) array.clone();
}
}
public static float[] clone(float array[]) {
if (array == null) {
return null;
} else {
return (float[]) (float[]) array.clone();
}
}
public static boolean[] clone(boolean array[]) {
if (array == null) {
return null;
} else {
return (boolean[]) (boolean[]) array.clone();
}
}
public static Object[] nullToEmpty(Object array[]) {
if (array == null || array.length == 0) {
return EMPTY_OBJECT_ARRAY;
} else {
return array;
}
}
public static String[] nullToEmpty(String array[]) {
if (array == null || array.length == 0) {
return EMPTY_STRING_ARRAY;
} else {
return array;
}
}
public static long[] nullToEmpty(long array[]) {
if (array == null || array.length == 0) {
return EMPTY_LONG_ARRAY;
} else {
return array;
}
}
public static int[] nullToEmpty(int array[]) {
if (array == null || array.length == 0) {
return EMPTY_INT_ARRAY;
} else {
return array;
}
}
public static short[] nullToEmpty(short array[]) {
if (array == null || array.length == 0) {
return EMPTY_SHORT_ARRAY;
} else {
return array;
}
}
public static char[] nullToEmpty(char array[]) {
if (array == null || array.length == 0) {
return EMPTY_CHAR_ARRAY;
} else {
return array;
}
}
public static byte[] nullToEmpty(byte array[]) {
if (array == null || array.length == 0) {
return EMPTY_BYTE_ARRAY;
} else {
return array;
}
}
public static double[] nullToEmpty(double array[]) {
if (array == null || array.length == 0) {
return EMPTY_DOUBLE_ARRAY;
} else {
return array;
}
}
public static float[] nullToEmpty(float array[]) {
if (array == null || array.length == 0) {
return EMPTY_FLOAT_ARRAY;
} else {
return array;
}
}
public static boolean[] nullToEmpty(boolean array[]) {
if (array == null || array.length == 0) {
return EMPTY_BOOLEAN_ARRAY;
} else {
return array;
}
}
public static Long[] nullToEmpty(Long array[]) {
if (array == null || array.length == 0) {
return EMPTY_LONG_OBJECT_ARRAY;
} else {
return array;
}
}
public static Integer[] nullToEmpty(Integer array[]) {
if (array == null || array.length == 0) {
return EMPTY_INTEGER_OBJECT_ARRAY;
} else {
return array;
}
}
public static Short[] nullToEmpty(Short array[]) {
if (array == null || array.length == 0) {
return EMPTY_SHORT_OBJECT_ARRAY;
} else {
return array;
}
}
public static Character[] nullToEmpty(Character array[]) {
if (array == null || array.length == 0) {
return EMPTY_CHARACTER_OBJECT_ARRAY;
} else {
return array;
}
}
public static Byte[] nullToEmpty(Byte array[]) {
if (array == null || array.length == 0) {
return EMPTY_BYTE_OBJECT_ARRAY;
} else {
return array;
}
}
public static Double[] nullToEmpty(Double array[]) {
if (array == null || array.length == 0) {
return EMPTY_DOUBLE_OBJECT_ARRAY;
} else {
return array;
}
}
public static Float[] nullToEmpty(Float array[]) {
if (array == null || array.length == 0) {
return EMPTY_FLOAT_OBJECT_ARRAY;
} else {
return array;
}
}
public static Boolean[] nullToEmpty(Boolean array[]) {
if (array == null || array.length == 0) {
return EMPTY_BOOLEAN_OBJECT_ARRAY;
} else {
return array;
}
}
public static Object[] subarray(Object 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 = ((Object) (array)).getClass().getComponentType();
if (newSize <= 0) {
return (Object[]) (Object[]) Array.newInstance(type, 0);
} else {
Object subarray[] = (Object[]) (Object[]) Array.newInstance(type,
newSize);
System.arraycopy(((Object) (array)), startIndexInclusive,
((Object) (subarray)), 0, newSize);
return subarray;
}
}
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;
} else {
long subarray[] = new long[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
}
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;
} else {
int subarray[] = new int[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
}
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;
} else {
short subarray[] = new short[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
}
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;
} else {
char subarray[] = new char[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
}
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;
} else {
byte subarray[] = new byte[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
}
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;
} else {
double subarray[] = new double[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
}
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;
} else {
float subarray[] = new float[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
}
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;
} else {
boolean subarray[] = new boolean[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
}
/**
* 描述 : (判断两个数组是否长度相等)
* 方法名: isSameLength
* 创建人:孙刚
* 创建时间:2014-1-22 上午11:09:51
* @param array1
* @param array2
* @return :boolean
*/
public static boolean isSameLength(Object array1[], Object array2[]) {
return (array1 != null || array2 == null || array2.length <= 0)
&& (array2 != null || array1 == null || array1.length <= 0)
&& (array1 == null || array2 == null || array1.length == array2.length);
}
public static boolean isSameLength(long array1[], long array2[]) {
return (array1 != null || array2 == null || array2.length <= 0)
&& (array2 != null || array1 == null || array1.length <= 0)
&& (array1 == null || array2 == null || array1.length == array2.length);
}
public static boolean isSameLength(int array1[], int array2[]) {
return (array1 != null || array2 == null || array2.length <= 0)
&& (array2 != null || array1 == null || array1.length <= 0)
&& (array1 == null || array2 == null || array1.length == array2.length);
}
public static boolean isSameLength(short array1[], short array2[]) {
return (array1 != null || array2 == null || array2.length <= 0)
&& (array2 != null || array1 == null || array1.length <= 0)
&& (array1 == null || array2 == null || array1.length == array2.length);
}
public static boolean isSameLength(char array1[], char array2[]) {
return (array1 != null || array2 == null || array2.length <= 0)
&& (array2 != null || array1 == null || array1.length <= 0)
&& (array1 == null || array2 == null || array1.length == array2.length);
}
public static boolean isSameLength(byte array1[], byte array2[]) {
return (array1 != null || array2 == null || array2.length <= 0)
&& (array2 != null || array1 == null || array1.length <= 0)
&& (array1 == null || array2 == null || array1.length == array2.length);
}
public static boolean isSameLength(double array1[], double array2[]) {
return (array1 != null || array2 == null || array2.length <= 0)
&& (array2 != null || array1 == null || array1.length <= 0)
&& (array1 == null || array2 == null || array1.length == array2.length);
}
public static boolean isSameLength(float array1[], float array2[]) {
return (array1 != null || array2 == null || array2.length <= 0)
&& (array2 != null || array1 == null || array1.length <= 0)
&& (array1 == null || array2 == null || array1.length == array2.length);
}
public static boolean isSameLength(boolean array1[], boolean array2[]) {
return (array1 != null || array2 == null || array2.length <= 0)
&& (array2 != null || array1 == null || array1.length <= 0)
&& (array1 == null || array2 == null || array1.length == array2.length);
}
/**
* 描述 : (获取一个数组的长度)
* 方法名: getLength
* 创建人:孙刚
* 创建时间:2014-1-22 上午11:13:44
* @param array
* @return :int
*/
public static int getLength(Object array) {
if (array == null) {
return 0;
} else {
return Array.getLength(array);
}
}
/**
* 描述 : (判断两个数组是否是相等的类型)
* 方法名: isSameType
* 创建人:孙刚
* 创建时间:2014-1-22 上午11:14:37
* @param array1
* @param array2
* @return :boolean
*/
public static boolean isSameType(Object array1, Object array2) {
if (array1 == null || array2 == null) {
throw new IllegalArgumentException("The Array must not be null");
} else {
return array1.getClass().getName().equals(
array2.getClass().getName());
}
}
/**
* 描述 : (反转数组内容)
* 方法名: reverse
* 创建人:孙刚
* 创建时间:2014-1-22 上午11:15:21
* @param array
* @return :void
*/
public static void reverse(Object array[]) {
if (array == null) {
return;
}
int i = 0;
for (int j = array.length - 1; j > i; i++) {
Object tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
}
}
public static void reverse(long array[]) {
if (array == null) {
return;
}
int i = 0;
for (int j = array.length - 1; j > i; i++) {
long tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
}
}
public static void reverse(int array[]) {
if (array == null) {
return;
}
int i = 0;
for (int j = array.length - 1; j > i; i++) {
int tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
}
}
public static void reverse(short array[]) {
if (array == null) {
return;
}
int i = 0;
for (int j = array.length - 1; j > i; i++) {
short tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
}
}
public static void reverse(char array[]) {
if (array == null) {
return;
}
int i = 0;
for (int j = array.length - 1; j > i; i++) {
char tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
}
}
public static void reverse(byte array[]) {
if (array == null) {
return;
}
int i = 0;
for (int j = array.length - 1; j > i; i++) {
byte tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
}
}
public static void reverse(double array[]) {
if (array == null) {
return;
}
int i = 0;
for (int j = array.length - 1; j > i; i++) {
double tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
}
}
public static void reverse(float array[]) {
if (array == null) {
return;
}
int i = 0;
for (int j = array.length - 1; j > i; i++) {
float tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
}
}
public static void reverse(boolean array[]) {
if (array == null) {
return;
}
int i = 0;
for (int j = array.length - 1; j > i; i++) {
boolean tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
}
}
/**
* 描述 : (获取指定内容所在数组下标位置,找不到返回 -1)
* 方法名: indexOf
* 创建人:孙刚
* 创建时间:2014-1-22 上午11:19:37
* @param array
* @param objectToFind
* @return :int
*/
public static int indexOf(Object array[], Object objectToFind) {
return indexOf(array, objectToFind, 0);
}
public static int indexOf(Object array[], Object objectToFind,
int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
startIndex = 0;
}
if (objectToFind == null) {
for (int i = startIndex; i < array.length; i++) {
if (array[i] == null) {
return i;
}
}
} else {
for (int i = startIndex; i < array.length; i++) {
if (objectToFind.equals(array[i])) {
return i;
}
}
}
return -1;
}
/**
* 描述 : (获取指定元素在数组中 最后一次出现的位置)
* 方法名: lastIndexOf
* 创建人:孙刚
* 创建时间:2014-1-22 上午11:22:48
* @param array
* @param objectToFind
* @return :int
*/
public static int lastIndexOf(Object array[], Object objectToFind) {
return lastIndexOf(array, objectToFind, 2147483647);
}
public static int lastIndexOf(Object array[], Object objectToFind,
int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
return -1;
}
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 {
for (int i = startIndex; i >= 0; i--) {
if (objectToFind.equals(array[i])) {
return i;
}
}
}
return -1;
}
/**
* 描述 : (判断一个数组中是否包含此元素)
* 方法名: contains
* 创建人:孙刚
* 创建时间:2014-1-22 上午11:40:01
* @param array
* @param objectToFind
* @return :boolean
*/
public static boolean contains(Object array[], Object objectToFind) {
return indexOf(array, objectToFind) != -1;
}
public static int indexOf(long array[], long valueToFind) {
return indexOf(array, valueToFind, 0);
}
public static int indexOf(long array[], long valueToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < array.length; i++) {
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
public static int lastIndexOf(long array[], long valueToFind) {
return lastIndexOf(array, valueToFind, 2147483647);
}
public static int lastIndexOf(long array[], long valueToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
return -1;
}
if (startIndex >= array.length) {
startIndex = array.length - 1;
}
for (int i = startIndex; i >= 0; i--) {
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
public static boolean contains(long array[], long valueToFind) {
return indexOf(array, valueToFind) != -1;
}
public static int indexOf(int array[], int valueToFind) {
return indexOf(array, valueToFind, 0);
}
public static int indexOf(int array[], int valueToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < array.length; i++) {
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
public static int lastIndexOf(int array[], int valueToFind) {
return lastIndexOf(array, valueToFind, 2147483647);
}
public static int lastIndexOf(int array[], int valueToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
return -1;
}
if (startIndex >= array.length) {
startIndex = array.length - 1;
}
for (int i = startIndex; i >= 0; i--) {
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
public static boolean contains(int array[], int valueToFind) {
return indexOf(array, valueToFind) != -1;
}
public static int indexOf(short array[], short valueToFind) {
return indexOf(array, valueToFind, 0);
}
public static int indexOf(short array[], short valueToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < array.length; i++) {
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
public static int lastIndexOf(short array[], short valueToFind) {
return lastIndexOf(array, valueToFind, 2147483647);
}
public static int lastIndexOf(short array[], short valueToFind,
int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
return -1;
}
if (startIndex >= array.length) {
startIndex = array.length - 1;
}
for (int i = startIndex; i >= 0; i--) {
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
public static boolean contains(short array[], short valueToFind) {
return indexOf(array, valueToFind) != -1;
}
public static int indexOf(char array[], char valueToFind) {
return indexOf(array, valueToFind, 0);
}
public static int indexOf(char array[], char valueToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < array.length; i++) {
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
public static int lastIndexOf(char array[], char valueToFind) {
return lastIndexOf(array, valueToFind, 2147483647);
}
public static int lastIndexOf(char array[], char valueToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
return -1;
}
if (startIndex >= array.length) {
startIndex = array.length - 1;
}
for (int i = startIndex; i >= 0; i--) {
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
public static boolean contains(char array[], char valueToFind) {
return indexOf(array, valueToFind) != -1;
}
public static int indexOf(byte array[], byte valueToFind) {
return indexOf(array, valueToFind, 0);
}
public static int indexOf(byte array[], byte valueToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < array.length; i++) {
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
public static int lastIndexOf(byte array[], byte valueToFind) {
return lastIndexOf(array, valueToFind, 2147483647);
}
public static int lastIndexOf(byte array[], byte valueToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
return -1;
}
if (startIndex >= array.length) {
startIndex = array.length - 1;
}
for (int i = startIndex; i >= 0; i--) {
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
public static boolean contains(byte array[], byte valueToFind) {
return indexOf(array, valueToFind) != -1;
}
public static int indexOf(double array[], double valueToFind) {
return indexOf(array, valueToFind, 0);
}
public static int indexOf(double array[], double valueToFind,
double tolerance) {
return indexOf(array, valueToFind, 0, tolerance);
}
public static int indexOf(double array[], double valueToFind, int startIndex) {
if (isEmpty(array)) {
return -1;
}
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < array.length; i++) {
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
public static int indexOf(double array[], double valueToFind,
int startIndex, double tolerance) {
if (isEmpty(array)) {
return -1;
}
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 -1;
}
public static int lastIndexOf(double array[], double valueToFind) {
return lastIndexOf(array, valueToFind, 2147483647);
}
public static int lastIndexOf(double array[], double valueToFind,
double tolerance) {
return lastIndexOf(array, valueToFind, 2147483647, tolerance);
}
public static int lastIndexOf(double array[], double valueToFind,
int startIndex) {
if (isEmpty(array)) {
return -1;
}
if (startIndex < 0) {
return -1;
}
if (startIndex >= array.length) {
startIndex = array.length - 1;
}
for (int i = startIndex; i >= 0; i--) {
if (valueToFind == array[i])
return i;
}
return -1;
}
public static int lastIndexOf(double array[], double valueToFind,
int startIndex, double tolerance) {
if (isEmpty(array)) {
return -1;
}
if (startIndex < 0) {
return -1;
}
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 -1;
}
public static boolean contains(double array[], double valueToFind) {
return indexOf(array, valueToFind) != -1;
}
public static boolean contains(double array[], double valueToFind,
double tolerance) {
return indexOf(array, valueToFind, 0, tolerance) != -1;
}
public static int indexOf(float array[], float valueToFind) {
return indexOf(array, valueToFind, 0);
}
public static int indexOf(float array[], float valueToFind, int startIndex) {
if (isEmpty(array)) {
return -1;
}
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < array.length; i++) {
if (valueToFind == array[i])
return i;
}
return -1;
}
public static int lastIndexOf(float array[], float valueToFind) {
return lastIndexOf(array, valueToFind, 2147483647);
}
public static int lastIndexOf(float array[], float valueToFind,
int startIndex) {
if (isEmpty(array)) {
return -1;
}
if (startIndex < 0) {
return -1;
}
if (startIndex >= array.length) {
startIndex = array.length - 1;
}
for (int i = startIndex; i >= 0; i--) {
if (valueToFind == array[i])
return i;
}
return -1;
}
public static boolean contains(float array[], float valueToFind) {
return indexOf(array, valueToFind) != -1;
}
public static int indexOf(boolean array[], boolean valueToFind) {
return indexOf(array, valueToFind, 0);
}
public static int indexOf(boolean array[], boolean valueToFind,
int startIndex) {
if (isEmpty(array)) {
return -1;
}
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < array.length; i++) {
if (valueToFind == array[i])
return i;
}
return -1;
}
public static int lastIndexOf(boolean array[], boolean valueToFind) {
return lastIndexOf(array, valueToFind, 2147483647);
}
public static int lastIndexOf(boolean array[], boolean valueToFind,
int startIndex) {
if (isEmpty(array)) {
return -1;
}
if (startIndex < 0) {
return -1;
}
if (startIndex >= array.length) {
startIndex = array.length - 1;
}
for (int i = startIndex; i >= 0; i--) {
if (valueToFind == array[i])
return i;
}
return -1;
}
public static boolean contains(boolean array[], boolean valueToFind) {
return indexOf(array, valueToFind) != -1;
}
public static char[] toPrimitive(Character array[]) {
if (array == null) {
return null;
}
if (array.length == 0) {
return EMPTY_CHAR_ARRAY;
}
char result[] = new char[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = array[i].charValue();
}
return result;
}
public static char[] toPrimitive(Character array[], char valueForNull) {
if (array == null) {
return null;
}
if (array.length == 0) {
return EMPTY_CHAR_ARRAY;
}
char result[] = new char[array.length];
for (int i = 0; i < array.length; i++) {
Character b = array[i];
result[i] = b != null ? b.charValue() : valueForNull;
}
return result;
}
public static Character[] toObject(char array[]) {
if (array == null) {
return null;
}
if (array.length == 0) {
return EMPTY_CHARACTER_OBJECT_ARRAY;
}
Character result[] = new Character[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = new Character(array[i]);
}
return result;
}
public static long[] toPrimitive(Long array[]) {
if (array == null) {
return null;
}
if (array.length == 0) {
return EMPTY_LONG_ARRAY;
}
long result[] = new long[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = array[i].longValue();
}
return result;
}
public static long[] toPrimitive(Long array[], long valueForNull) {
if (array == null) {
return null;
}
if (array.length == 0) {
return EMPTY_LONG_ARRAY;
}
long result[] = new long[array.length];
for (int i = 0; i < array.length; i++) {
Long b = array[i];
result[i] = b != null ? b.longValue() : valueForNull;
}
return result;
}
public static Long[] toObject(long array[]) {
if (array == null) {
return null;
}
if (array.length == 0) {
return EMPTY_LONG_OBJECT_ARRAY;
}
Long result[] = new Long[array.length];
for (int i = 0; i < array.length; i++){
result[i] = new Long(array[i]);
}
return result;
}
public static int[] toPrimitive(Integer array[]) {
if (array == null){
return null;
}
if (array.length == 0) {{
return EMPTY_INT_ARRAY;
}
}
int result[] = new int[array.length];
for (int i = 0; i < array.length; i++){
result[i] = array[i].intValue();
}
return result;
}
public static int[] toPrimitive(Integer array[], int valueForNull) {
if (array == null){
return null;
}
if (array.length == 0){
return EMPTY_INT_ARRAY;
}
int result[] = new int[array.length];
for (int i = 0; i < array.length; i++) {
Integer b = array[i];
result[i] = b != null ? b.intValue() : valueForNull;
}
return result;
}
/**
* 描述 : (将一个基本类型数组 装换成对应的包装类的类型)
* 方法名: toObject
* 创建人:孙刚
* 创建时间:2014-2-8 下午03:14:53
* @param array
* @return
* @return :Integer[]
*/
public static Integer[] toObject(int array[]) {
if (array == null){
return null;
}
if (array.length == 0){
return EMPTY_INTEGER_OBJECT_ARRAY;
}
Integer result[] = new Integer[array.length];
for (int i = 0; i < array.length; i++){
result[i] = new Integer(array[i]);
}
return result;
}
public static short[] toPrimitive(Short array[]) {
if (array == null){
return null;
}
if (array.length == 0){
return EMPTY_SHORT_ARRAY;
}
short result[] = new short[array.length];
for (int i = 0; i < array.length; i++){
result[i] = array[i].shortValue();
}
return result;
}
public static short[] toPrimitive(Short array[], short valueForNull) {
if (array == null){
return null;
}
if (array.length == 0){
return EMPTY_SHORT_ARRAY;
}
short result[] = new short[array.length];
for (int i = 0; i < array.length; i++) {
Short b = array[i];
result[i] = b != null ? b.shortValue() : valueForNull;
}
return result;
}
public static Short[] toObject(short array[]) {
if (array == null){
return null;
}
if (array.length == 0){
return EMPTY_SHORT_OBJECT_ARRAY;
}
Short result[] = new Short[array.length];
for (int i = 0; i < array.length; i++){
result[i] = new Short(array[i]);
}
return result;
}
public static byte[] toPrimitive(Byte array[]) {
if (array == null){
return null;
}
if (array.length == 0){
return EMPTY_BYTE_ARRAY;
}
byte result[] = new byte[array.length];
for (int i = 0; i < array.length; i++){
result[i] = array[i].byteValue();
}
return result;
}
public static byte[] toPrimitive(Byte array[], byte valueForNull) {
if (array == null){
return null;
}
if (array.length == 0){
return EMPTY_BYTE_ARRAY;
}
byte result[] = new byte[array.length];
for (int i = 0; i < array.length; i++) {
Byte b = array[i];
result[i] = b != null ? b.byteValue() : valueForNull;
}
return result;
}
public static Byte[] toObject(byte array[]) {
if (array == null){
return null;
}
if (array.length == 0){
return EMPTY_BYTE_OBJECT_ARRAY;
}
Byte result[] = new Byte[array.length];
for (int i = 0; i < array.length; i++){
result[i] = new Byte(array[i]);
}
return result;
}
public static double[] toPrimitive(Double array[]) {
if (array == null){
return null;
}
if (array.length == 0){
return EMPTY_DOUBLE_ARRAY;
}
double result[] = new double[array.length];
for (int i = 0; i < array.length; i++){
result[i] = array[i].doubleValue();
}
return result;
}
public static double[] toPrimitive(Double array[], double valueForNull) {
if (array == null){
return null;
}
if (array.length == 0){
return EMPTY_DOUBLE_ARRAY;
}
double result[] = new double[array.length];
for (int i = 0; i < array.length; i++) {
Double b = array[i];
result[i] = b != null ? b.doubleValue() : valueForNull;
}
return result;
}
public static Double[] toObject(double array[]) {
if (array == null){
return null;
}
if (array.length == 0){
return EMPTY_DOUBLE_OBJECT_ARRAY;
}
Double result[] = new Double[array.length];
for (int i = 0; i < array.length; i++){
result[i] = new Double(array[i]);
}
return result;
}
public static float[] toPrimitive(Float array[]) {
if (array == null){
return null;
}
if (array.length == 0){
return EMPTY_FLOAT_ARRAY;
}
float result[] = new float[array.length];
for (int i = 0; i < array.length; i++){
result[i] = array[i].floatValue();
}
return result;
}
public static float[] toPrimitive(Float array[], float valueForNull) {
if (array == null){
return null;
}
if (array.length == 0){
return EMPTY_FLOAT_ARRAY;
}
float result[] = new float[array.length];
for (int i = 0; i < array.length; i++) {
Float b = array[i];
result[i] = b != null ? b.floatValue() : valueForNull;
}
return result;
}
public static Float[] toObject(float array[]) {
if (array == null){
return null;
}
if (array.length == 0){
return EMPTY_FLOAT_OBJECT_ARRAY;
}
Float result[] = new Float[array.length];
for (int i = 0; i < array.length; i++){
result[i] = new Float(array[i]);
}
return result;
}
public static boolean[] toPrimitive(Boolean array[]) {
if (array == null){
return null;
}
if (array.length == 0){
return EMPTY_BOOLEAN_ARRAY;
}
boolean result[] = new boolean[array.length];
for (int i = 0; i < array.length; i++){
result[i] = array[i].booleanValue();
}
return result;
}
public static boolean[] toPrimitive(Boolean array[], boolean valueForNull) {
if (array == null){
return null;
}
if (array.length == 0){
return EMPTY_BOOLEAN_ARRAY;
}
boolean result[] = new boolean[array.length];
for (int i = 0; i < array.length; i++) {
Boolean b = array[i];
result[i] = b != null ? b.booleanValue() : valueForNull;
}
return result;
}
public static Boolean[] toObject(boolean array[]) {
if (array == null){
return null;
}
if (array.length == 0){
return EMPTY_BOOLEAN_OBJECT_ARRAY;
}
Boolean result[] = new Boolean[array.length];
for (int i = 0; i < array.length; i++){
result[i] = array[i] ? Boolean.TRUE : Boolean.FALSE;
}
return result;
}
/**
* 描述 : (判断一个数组是否为 null 为null 时返回 true)
* 方法名: isEmpty
* 创建人:孙刚
* 创建时间:2014-2-8 下午03:17:47
* @param array
* @return
* @return :boolean
*/
public static boolean isEmpty(Object array[]) {
return array == null || array.length == 0;
}
public static boolean isEmpty(long array[]) {
return array == null || array.length == 0;
}
public static boolean isEmpty(int array[]) {
return array == null || array.length == 0;
}
public static boolean isEmpty(short array[]) {
return array == null || array.length == 0;
}
public static boolean isEmpty(char array[]) {
return array == null || array.length == 0;
}
public static boolean isEmpty(byte array[]) {
return array == null || array.length == 0;
}
public static boolean isEmpty(double array[]) {
return array == null || array.length == 0;
}
public static boolean isEmpty(float array[]) {
return array == null || array.length == 0;
}
public static boolean isEmpty(boolean array[]) {
return array == null || array.length == 0;
}
/**
* 描述 : (判断一个数组不为null 不为 null时 返回 true)
* 方法名: isNotEmpty
* 创建人:孙刚
* 创建时间:2014-2-8 下午03:18:23
* @param array
* @return
* @return :boolean
*/
public static boolean isNotEmpty(Object array[]) {
return array != null && array.length != 0;
}
public static boolean isNotEmpty(long array[]) {
return array != null && array.length != 0;
}
public static boolean isNotEmpty(int array[]) {
return array != null && array.length != 0;
}
public static boolean isNotEmpty(short array[]) {
return array != null && array.length != 0;
}
public static boolean isNotEmpty(char array[]) {
return array != null && array.length != 0;
}
public static boolean isNotEmpty(byte array[]) {
return array != null && array.length != 0;
}
public static boolean isNotEmpty(double array[]) {
return array != null && array.length != 0;
}
public static boolean isNotEmpty(float array[]) {
return array != null && array.length != 0;
}
public static boolean isNotEmpty(boolean array[]) {
return array != null && array.length != 0;
}
/**
* 描述 : (将两个数组 合并为一个数组)
* 方法名: addAll
* 创建人:孙刚
* 创建时间:2014-1-22 下午02:36:32
* @param array1
* @param array2
* @return
* @return :Object[]
*/
public static Object[] addAll(Object array1[], Object array2[]) {
if (array1 == null){
return clone(array2);
}
if (array2 == null){
return clone(array1);
}
Object joinedArray[] = (Object[]) (Object[]) Array.newInstance(
((Object) (array1)).getClass().getComponentType(),
array1.length + array2.length);
System.arraycopy(((Object) (array1)), 0, ((Object) (joinedArray)), 0,array1.length);
try {
System.arraycopy(((Object) (array2)), 0, ((Object) (joinedArray)),
array1.length, array2.length);
} catch (ArrayStoreException ase) {
Class type1 = ((Object) (array1)).getClass().getComponentType();
Class type2 = ((Object) (array2)).getClass().getComponentType();
if (!type1.isAssignableFrom(type2)){
throw new IllegalArgumentException("Cannot store "
+ type2.getName() + " in an array of "
+ type1.getName());
}else{
throw ase;
}
}
return joinedArray;
}
public static boolean[] addAll(boolean array1[], boolean array2[]) {
if (array1 == null){
return clone(array2);
}
if (array2 == null) {
return clone(array1);
} else {
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;
}
}
public static char[] addAll(char array1[], char array2[]) {
if (array1 == null){
return clone(array2);
}
if (array2 == null) {
return clone(array1);
} else {
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;
}
}
public static byte[] addAll(byte array1[], byte array2[]) {
if (array1 == null){
return clone(array2);
}
if (array2 == null) {
return clone(array1);
} else {
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;
}
}
public static short[] addAll(short array1[], short array2[]) {
if (array1 == null){
return clone(array2);
}
if (array2 == null) {
return clone(array1);
} else {
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;
}
}
public static int[] addAll(int array1[], int array2[]) {
if (array1 == null){
return clone(array2);
}
if (array2 == null) {
return clone(array1);
} else {
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;
}
}
public static long[] addAll(long array1[], long array2[]) {
if (array1 == null){
return clone(array2);
}
if (array2 == null) {
return clone(array1);
} else {
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;
}
}
public static float[] addAll(float array1[], float array2[]) {
if (array1 == null){
return clone(array2);
}
if (array2 == null) {
return clone(array1);
} else {
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;
}
}
public static double[] addAll(double array1[], double array2[]) {
if (array1 == null){
return clone(array2);
}
if (array2 == null) {
return clone(array1);
} else {
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;
}
}
/**
* 描述 : (将某个元素 放入到指定的数组中)
* 方法名: add
* 创建人:孙刚
* 创建时间:2014-1-22 下午02:37:22
* @param array
* @param element
* @return
* @return :Object[]
*/
public static Object[] add(Object array[], Object element) {
Class type;
if (array != null){
type = ((Object) (array)).getClass();
}else if (element != null){
type = element.getClass();
}else{
type = java.lang.Object.class;
}
Object newArray[] = (Object[]) (Object[]) copyArrayGrow1(((Object) (array)), type);
newArray[newArray.length - 1] = element;
return newArray;
}
public static boolean[] add(boolean array[], boolean element) {
boolean newArray[] = (boolean[]) (boolean[]) copyArrayGrow1(array,Boolean.TYPE);
newArray[newArray.length - 1] = element;
return newArray;
}
public static byte[] add(byte array[], byte element) {
byte newArray[] = (byte[]) (byte[]) copyArrayGrow1(array, Byte.TYPE);
newArray[newArray.length - 1] = element;
return newArray;
}
public static char[] add(char array[], char element) {
char newArray[] = (char[]) (char[]) copyArrayGrow1(array,Character.TYPE);
newArray[newArray.length - 1] = element;
return newArray;
}
public static double[] add(double array[], double element) {
double newArray[] = (double[]) (double[]) copyArrayGrow1(array,Double.TYPE);
newArray[newArray.length - 1] = element;
return newArray;
}
public static float[] add(float array[], float element) {
float newArray[] = (float[]) (float[]) copyArrayGrow1(array, Float.TYPE);
newArray[newArray.length - 1] = element;
return newArray;
}
public static int[] add(int array[], int element) {
int newArray[] = (int[]) (int[]) copyArrayGrow1(array, Integer.TYPE);
newArray[newArray.length - 1] = element;
return newArray;
}
public static long[] add(long array[], long element) {
long newArray[] = (long[]) (long[]) copyArrayGrow1(array, Long.TYPE);
newArray[newArray.length - 1] = element;
return newArray;
}
public static short[] add(short array[], short element) {
short newArray[] = (short[]) (short[]) copyArrayGrow1(array, Short.TYPE);
newArray[newArray.length - 1] = element;
return newArray;
}
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;
} else {
return Array.newInstance(newArrayComponentType, 1);
}
}
public static Object[] add(Object array[], int index, Object element) {
Class clss = null;
if (array != null){
clss = ((Object) (array)).getClass().getComponentType();
}else if (element != null){
clss = element.getClass();
}else{
return (new Object[] { null });
}
return (Object[]) (Object[]) add(((Object) (array)), index, element,clss);
}
public static boolean[] add(boolean array[], int index, boolean element) {
return (boolean[]) (boolean[]) add(array, index, BooleanUtils.toBooleanObject(element), Boolean.TYPE);
}
public static char[] add(char array[], int index, char element) {
return (char[]) (char[]) add(array, index, new Character(element),Character.TYPE);
}
public static byte[] add(byte array[], int index, byte element) {
return (byte[]) (byte[]) add(array, index, new Byte(element), Byte.TYPE);
}
public static short[] add(short array[], int index, short element) {
return (short[]) (short[]) add(array, index, new Short(element),Short.TYPE);
}
public static int[] add(int array[], int index, int element) {
return (int[]) (int[]) add(array, index, new Integer(element),Integer.TYPE);
}
public static long[] add(long array[], int index, long element) {
return (long[]) (long[]) add(array, index, new Long(element), Long.TYPE);
}
public static float[] add(float array[], int index, float element) {
return (float[]) (float[]) add(array, index, new Float(element),Float.TYPE);
}
public static double[] add(double array[], int index, double element) {
return (double[]) (double[]) add(array, index, new Double(element),Double.TYPE);
}
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");
} else {
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;
}
/**
* 描述 : (删除一个数组 中指定下标位置的元素)
* 方法名: remove
* 创建人:孙刚
* 创建时间:2014-1-22 下午02:39:43
* @param array
* @param index
* @return
* @return :Object[]
*/
public static Object[] remove(Object array[], int index) {
return (Object[]) (Object[]) remove(((Object) (array)), index);
}
/**
* 描述 : (删除一个数组 中指定的元素)
* 方法名: removeElement
* 创建人:孙刚
* 创建时间:2014-1-22 下午02:39:50
* @param array
* @param element
* @return
* @return :Object[]
*/
public static Object[] removeElement(Object array[], Object element) {
int index = indexOf(array, element);
if (index == -1){
return clone(array);
}else{
return remove(array, index);
}
}
public static boolean[] remove(boolean array[], int index) {
return (boolean[]) (boolean[]) remove(array, index);
}
public static boolean[] removeElement(boolean array[], boolean element) {
int index = indexOf(array, element);
if (index == -1){
return clone(array);
}else{
return remove(array, index);
}
}
public static byte[] remove(byte array[], int index) {
return (byte[]) (byte[]) remove(array, index);
}
public static byte[] removeElement(byte array[], byte element) {
int index = indexOf(array, element);
if (index == -1){
return clone(array);
}else{
return remove(array, index);
}
}
public static char[] remove(char array[], int index) {
return (char[]) (char[]) remove(array, index);
}
public static char[] removeElement(char array[], char element) {
int index = indexOf(array, element);
if (index == -1){
return clone(array);
}else{
return remove(array, index);
}
}
public static double[] remove(double array[], int index) {
return (double[]) (double[]) remove(array, index);
}
public static double[] removeElement(double array[], double element) {
int index = indexOf(array, element);
if (index == -1){
return clone(array);
}else{
return remove(array, index);
}
}
public static float[] remove(float array[], int index) {
return (float[]) (float[]) remove(array, index);
}
public static float[] removeElement(float array[], float element) {
int index = indexOf(array, element);
if (index == -1){
return clone(array);
}else{
return remove(array, index);
}
}
public static int[] remove(int array[], int index) {
return (int[]) (int[]) remove(array, index);
}
public static int[] removeElement(int array[], int element) {
int index = indexOf(array, element);
if (index == -1){
return clone(array);
}else{
return remove(array, index);
}
}
public static long[] remove(long array[], int index) {
return (long[]) (long[]) remove(array, index);
}
public static long[] removeElement(long array[], long element) {
int index = indexOf(array, element);
if (index == -1){
return clone(array);
}else{
return remove(array, index);
}
}
public static short[] remove(short array[], int index) {
return (short[]) (short[]) remove(array, index);
}
public static short[] removeElement(short array[], short element) {
int index = indexOf(array, element);
if (index == -1){
return clone(array);
}else{
return remove(array, index);
}
}
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;
}
}
|
package com.sg.base;
import java.io.Serializable;
import java.util.LinkedHashMap;
import com.sg.utils.Pager;
/**
* 实体操作通用接口
*
* @author Administrator
*
* @param <T>
*/
public interface DAO<T> {
/**
* 保存实体
*
* @param entity
*/
void save(T entity);
/**
* 更新实体
*
* @param entity
*/
void update(T entity);
/**
* 删除实体
*
* @param id
*/
void delete(Serializable id);
/**
* 查找实体
*
* @param id
* @return
*/
T find(Serializable id);
/**
* 查找实体
* @param username
* @return
*/
T find(String username);
/**
* 获取总记录数
*
* @return
*/
long getCount();
/**
* 分页查询
* @param firstResult当前页
* @param maxResult每页显示多少条
* @param where 是否有where条件(格式 )name = ?1 无需在家 where关键字
* @param params 参数 new Object[]{"张三"}
* @param orderBy 排序 格式 key为 xxx value为desc/asc map.put("create_date","desc")
* @return
*/
Pager<T> getResultForPager(int firstResult,int maxResult,String where,Object[] params,LinkedHashMap<String, String> orderBy);
/**
* 分页查询
* @param firstResult 当前页
* @param maxResult 每页显示多少条
* @param where 是否有where条件
* @param params参数
* @return
*/
Pager<T> getResultForPager(int firstResult,int maxResult,String where,Object[] params);
/**
* 分页查询
* @param firstResult
* @param maxResult
* @param orderBy
* @return
*/
Pager<T> getResultForPager(int firstResult,int maxResult,LinkedHashMap<String, String> orderBy);
/**
* 分页查询
* @param firstResult
* @param maxResult
* @return
*/
Pager<T> getResultForPager(int firstResult,int maxResult);
}
package com.sg.dao.impl;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import com.sg.base.DAO;
import com.sg.utils.Pager;
public abstract class DaoSupport<T> implements DAO<T> {
@PersistenceContext
protected EntityManager manager;
/**
* 实体类
*/
protected Class<T> entityClass = getEntityClass();
/**
* 得到运行时类第一个泛型实体对象Class
*
* @return
*/
@SuppressWarnings("unchecked")
public Class<T> getEntityClass() {
// 获取父类泛型类
Type type = getClass().getGenericSuperclass();
// 判断是否是一个泛型类
if (type instanceof ParameterizedType) {
// 转换成泛型类
ParameterizedType pType = (ParameterizedType) type;
// 得到所有泛型类型
// Type[] types = pType.getActualTypeArguments();
// 得到第一个泛型Class对象
return (Class<T>) pType.getActualTypeArguments()[0];
}
return null;
}
@Override
public void save(T entity) {
manager.persist(entity);
}
@Override
public void update(T entity) {
manager.merge(entity);
}
@Override
public void delete(Serializable id) {
manager.remove(manager.getReference(entityClass, id));
}
@Override
public T find(Serializable id) {
return manager.find(entityClass, id);
}
@Override
public T find(String username) {
String sqlString = "select o from " + this.getEntityName(entityClass) + " o where o.username = ?1";
Query query = manager.createQuery(sqlString);
query.setParameter(1, username);
return (T) query.getSingleResult();
}
@Override
public long getCount() {
String sqlString = "select count(o) from " + this.getEntityName(this.entityClass)+ " o";
Long count = (Long) manager.createQuery(sqlString).getSingleResult();
return count;
}
/**
* 得到运行时类泛型实体名字
*
* @return
*/
public <E> String getEntityName(Class<E> entityClass) {
String entityName = this.entityClass.getSimpleName();
Entity entity = this.entityClass.getAnnotation(Entity.class);
// 判断
if (null != entity.name() && !"".equals(entity.name())) {
entityName = entity.name();
}
return entityName;
}
@Override
public Pager<T> getResultForPager(int firstResult, int maxResult) {
return getResultForPager(firstResult, maxResult, null, null, null);
}
@Override
public Pager<T> getResultForPager(int firstResult, int maxResult,
LinkedHashMap<String, String> orderBy) {
return getResultForPager(firstResult, maxResult, null, null, orderBy);
}
@Override
public Pager<T> getResultForPager(int firstResult, int maxResult,
String where, Object[] params) {
return getResultForPager(firstResult, maxResult, where, params, null);
}
@SuppressWarnings("unchecked")
@Override
public Pager<T> getResultForPager(int firstResult, int maxResult,
String where, Object[] params, LinkedHashMap<String, String> orderBy) {
String sqlString = "";
Pager pager = new Pager<T>();
String entityname = getEntityName(this.entityClass);
where = where == null || "".equals(where.trim()) ? "" : "where "+ where;
sqlString = "select o from "+ entityname + " o " + where + buildOrderBy(orderBy);
Query query = manager.createQuery(sqlString);
setQueryParams(query, params);
if (firstResult != -1 && maxResult != -1){
query.setFirstResult(firstResult).setMaxResults(maxResult);
}
//设置查询结果集
pager.setResultList(query.getResultList());
sqlString = "select count("+ getCountField(this.entityClass) + ") from " + entityname+ " o " + where;
query = manager.createQuery(sqlString);
setQueryParams(query, params);
//设置查询总数
pager.setResultTotal((Long) query.getSingleResult());
return pager;
}
/**
* 设置查询参数
*
* @param query
* @param params
*/
private static void setQueryParams(Query query, Object[] params){
if(params!=null && params.length>0){
for(int i=0; i<params.length; i++){
query.setParameter(i+1, params[i]);
}
}
}
/**
* 构建排序语句
*
* @param orderBy
* {xxx desc,xxx,asc} 排序属性 key为属性 value为asc/desc
* @return
*/
private static String buildOrderBy(LinkedHashMap<String, String> orderBy) {
StringBuffer buffer = new StringBuffer();
if (null != orderBy && !orderBy.isEmpty()) {
buffer.append(" order by ");
for (Map.Entry<String, String> entry : orderBy.entrySet()) {
buffer.append(" o.").append(entry.getKey()).append(" ")
.append(entry.getValue()).append(",");
}
// 删除最后一个 ,
buffer.deleteCharAt(buffer.length() - 1);
}
return buffer.toString();
}
/**
* 获取统计属性,该方法是为了解决hibernate解析联合主键select count(o) from Xxx
* o语句BUG而增加,hibernate对此jpql解析后的sql为select
* count(field1,field2,...),显示使用count()统计多个字段是错误的
*
* @param <E>
* @param clazz
* @return
*/
private static <E> String getCountField(Class<E> clazz) {
String out = "o";
try {
PropertyDescriptor[] propertyDescriptors = Introspector
.getBeanInfo(clazz).getPropertyDescriptors();
for (PropertyDescriptor propertydesc : propertyDescriptors) {
Method method = propertydesc.getReadMethod();
if (method != null
&& method.isAnnotationPresent(EmbeddedId.class)) {
PropertyDescriptor[] ps = Introspector.getBeanInfo(
propertydesc.getPropertyType())
.getPropertyDescriptors();
out = "o."
+ propertydesc.getName()
+ "."
+ (!ps[1].getName().equals("class") ? ps[1]
.getName() : ps[0].getName());
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return out;
}
}
package com.sg.base;
import com.opensymphony.xwork2.ActionSupport;
public class BaseAction extends ActionSupport {
/**
* 当前页
*/
private int currentPage = 1;
/**
* 每页显示数量
*/
private int maxResult = 15;
/**
* 判断是否是条件查询
*/
private String query;
public int getMaxResult() {
return maxResult;
}
public void setMaxResult(int maxResult) {
this.maxResult = maxResult;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
}
package com.sg.bean;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* 用户实体
*
* @author
*
*/
@Entity
public class Buyer implements Serializable {
/**
* 主键ID
*/
private int id;
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 真实姓名
*/
private String realname;
/**
* 邮箱
*/
private String email;
/**
* 性别
*/
private Gender gender = Gender.MAN;
/**
* 用户联系信息
*/
private ContactInfo contactInfo;
/**
* 是否启用 默认 可用
*/
private boolean visible = true;
/**
* 创建时间
*/
private Date create_time = new Date();
@Id
@GeneratedValue
@Column(length = 20)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(length = 100, nullable = false)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Column(length = 100, nullable = false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(length = 50)
public String getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname;
}
@Column(length = 100, nullable = false)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Enumerated(EnumType.STRING)
@Column(length = 5, nullable = false)
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
@OneToOne(cascade = CascadeType.ALL)
//外键名称
@JoinColumn(name="contant_id")
public ContactInfo getContactInfo() {
return contactInfo;
}
public void setContactInfo(ContactInfo contactInfo) {
this.contactInfo = contactInfo;
}
@Column(length = 10, nullable = false)
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(nullable = false)
public Date getCreate_time() {
return create_time;
}
public void setCreate_time(Date create_time) {
this.create_time = create_time;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((username == null) ? 0 : username.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Buyer other = (Buyer) obj;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
}
package com.sg.service;
import com.sg.base.DAO;
import com.sg.bean.Buyer;
public interface IBuyerService extends DAO<Buyer> {
/**
* 验证用户名是否存在
*
* @param username
* @return
*/
boolean exsit(String username);
/**
* 登录验证
* @param username
* @param password
* @return
*/
boolean validate(String username,String password);
}
package com.sg.service.impl;
import javax.persistence.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.sg.bean.Buyer;
import com.sg.dao.impl.DaoSupport;
import com.sg.service.IBuyerService;
import com.sg.utils.MD5;
@Service
@Transactional
// 事务
public class BuyerServiceImpl extends DaoSupport<Buyer> implements
IBuyerService {
@Override
public boolean exsit(String username) {
Query query = manager
.createQuery("select count(o) from Buyer o where o.username = ?1");
// 设置参数
query.setParameter(1, username);
long count = (Long) query.getSingleResult();
return count > 0;
}
@Override
public void save(Buyer entity) {
entity.setPassword(MD5.MD5Encode(entity.getPassword()));
super.save(entity);
}
@Override
public boolean validate(String username, String password) {
Query query = manager
.createQuery("select count(o) from Buyer o where o.username = ?1 and o.password = ?2");
long result = (Long) query.setParameter(1, username)
.setParameter(2, MD5.MD5Encode(password)).getSingleResult();
return result > 0;
}
}
package com.sg.action;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.sg.base.BaseAction;
import com.sg.bean.Buyer;
import com.sg.service.IBuyerService;
import com.sg.utils.Pager;
import com.sg.utils.PagerView;
import com.sg.utils.StrutsUtils;
public class BuyerAction extends BaseAction {
@Resource
private IBuyerService buyerService;
private Buyer buyer;
/**
* 跳转注册页面
*
*/
public String regUI() {
return "regUI";
}
/**
* 注册
*
* @return
*/
public String reg() {
HttpServletRequest request = StrutsUtils.getRequest();
if (buyerService.exsit(buyer.getUsername().trim())) {
request.setAttribute("error", "该用户已经存在!");
return "regUI";
} else {
buyerService.save(buyer);
request.setAttribute("message", "用户注册成功!");
request.setAttribute("urladdress", "/");
}
return "message";
}
/**
* 验证用户名是否已经存在
*
* @throws Exception
* @return
*/
public String isUserExsit() throws Exception {
HttpServletRequest request = StrutsUtils.getRequest();
request.setAttribute("exsit",
buyerService.exsit(buyer.getUsername().trim()));
return "checkResult";
}
/**
* 登陆跳转
*
* @return
*/
public String loginSkip() {
return "loginSkip";
}
/**
* 登陆
*
* @return
*/
public String login() {
HttpServletRequest request = StrutsUtils.getRequest();
if (null != buyer.getUsername() && !"".equals(buyer.getUsername())
&& null != buyer.getPassword()
&& !"".equals(buyer.getPassword())) {
// 验证登陆信息是否正确
if (buyerService.validate(buyer.getUsername(), buyer.getPassword())) {
request.getSession().setAttribute("user",
buyerService.find(buyer.getUsername()));
request.setAttribute("message", "用戶登陆成功!");
request.setAttribute("urladdress", "/");
return "message";
} else {
request.setAttribute("message", "用戶名或密码不正确!");
return "loginSkip";
}
}
return null;
}
/**
* 获取用户列表
*
* @return
*/
public String getUserList() {
HttpServletRequest request = StrutsUtils.getRequest();
int currentPage = super.getCurrentPage();
currentPage = -1 == currentPage || 0 == currentPage ? 1 : currentPage;
PagerView<Buyer> pagerView = new PagerView<Buyer>(super.getMaxResult(),
currentPage);
LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
orderBy.put("create_time", "desc");
Pager<Buyer> pager = null;
// 判断是否是条件查询
if ("true".equals(super.getQuery())) {
StringBuffer buffer = new StringBuffer();
List<Object> params = new ArrayList<Object>();
if (null != buyer.getUsername() && !"".equals(buyer.getUsername())) {
params.add("%" + buyer.getUsername() + "%");
buffer.append(" username like ?").append(params.size());
}
if (null != buyer.getRealname() && !"".equals(buyer.getRealname())) {
if (!params.isEmpty()) {
buffer.append(" and ");
}
params.add("%" + buyer.getRealname() + "%");
buffer.append(" realname like ?").append(params.size());
}
if (null != buyer.getEmail() && !"".equals(buyer.getEmail())) {
if (!params.isEmpty()) {
buffer.append(" and ");
}
params.add("%" + buyer.getEmail() + "%");
buffer.append(" email like ?").append(params.size());
}
pager = buyerService.getResultForPager(pagerView.getFirstResult(),
pagerView.getMaxResult(), buffer.toString(),
params.toArray(), orderBy);
} else {
pager = buyerService.getResultForPager(pagerView.getFirstResult(),
pagerView.getMaxResult(), orderBy);
}
pagerView.setQueryResult(pager);
request.setAttribute("pageView", pagerView);
return "userList";
}
/**
* 用户查询跳转
*
* @return
*/
public String querySkip() {
return "querySkip";
}
public Buyer getBuyer() {
return buyer;
}
public void setBuyer(Buyer buyer) {
this.buyer = buyer;
}
}
|
package org.sg.sgg.sort;
public enum SortType {
/**
* 选择排序
* Selection Sorting
*/
SELECTION(new Sortable() {
public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {
int len = array.length;
for (int i = 0; i < len; i++) {
int selected = i;
for (int j = i + 1; j < len; j++) {
int compare = array[j].compareTo(array[selected]);
if (compare != 0 && compare < 0 == ascend) {
selected = j;
}
}
exchange(array, i, selected);
}
}
}),
/**
* 插入排序
* Insertion Sorting
*/
INSERTION(new Sortable() {
public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {
int len = array.length;
for (int i = 1; i < len; i++) {
T toInsert = array[i];
int j = i;
for (; j > 0; j--) {
int compare = array[j - 1].compareTo(toInsert);
if (compare == 0 || compare < 0 == ascend) {
break;
}
array[j] = array[j - 1];
}
array[j] = toInsert;
}
}
}),
/**
* 冒泡排序
* Bubble Sorting, it's very similar with Insertion Sorting
*/
BUBBLE(new Sortable() {
public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {
int length = array.length;
int lastExchangedIdx = 0;
for (int i = 0; i < length; i++) {
// mark the flag to identity whether exchange happened to false
boolean isExchanged = false;
// last compare and exchange happened before reaching index i
int currOrderedIdx = lastExchangedIdx > i ? lastExchangedIdx : i;
for (int j = length - 1; j > currOrderedIdx; j--) {
int compare = array[j - 1].compareTo(array[j]);
if (compare != 0 && compare > 0 == ascend) {
exchange(array, j - 1, j);
isExchanged = true;
lastExchangedIdx = j;
}
}
// if no exchange happen means array is already in order
if (isExchanged == false) {
break;
}
}
}
}),
/**
* 壳(Shell)排序
* Shell Sorting
*/
SHELL(new Sortable() {
public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {
int length = array.length;
int gap = 1;
// use the most next to length / 3 as the first gap
while (gap < length / 3) {
gap = gap * 3 + 1;
}
while (gap >= 1) {
for (int i = gap; i < length; i++) {
T next = array[i];
int j = i;
while (j >= gap) {
int compare = array[j - gap].compareTo(next);
// already find its position
if (compare == 0 || compare < 0 == ascend) {
break;
}
array[j] = array[j - gap];
j -= gap;
}
if (j != i) {
array[j] = next;
}
}
gap /= 3;
}
}
}),
/**
* 归并排序
* Merge sorting
*/
MERGE(new Sortable() {
public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {
this.sort(array, 0, array.length - 1, ascend);
}
private <T extends Comparable<T>> void sort(T[] array, int lo, int hi, boolean ascend) {
// OPTIMIZE ONE
// if the substring's length is less than 20,
// use insertion sort to reduce recursive invocation
if (hi - lo < 20) {
for (int i = lo + 1; i <= hi; i++) {
T toInsert = array[i];
int j = i;
for (; j > lo; j--) {
int compare = array[j - 1].compareTo(toInsert);
if (compare == 0 || compare < 0 == ascend) {
break;
}
array[j] = array[j - 1];
}
array[j] = toInsert;
}
return;
}
int mid = lo + (hi - lo) / 2;
sort(array, lo, mid, ascend);
sort(array, mid + 1, hi, ascend);
merge(array, lo, mid, hi, ascend);
}
private <T extends Comparable<T>> void merge(T[] array, int lo, int mid, int hi, boolean ascend) {
// OPTIMIZE TWO
// if it is already in right order, skip this merge
// since there's no need to do so
int leftEndCompareToRigthStart = array[mid].compareTo(array[mid + 1]);
if (leftEndCompareToRigthStart == 0 || leftEndCompareToRigthStart < 0 == ascend) {
return;
}
@SuppressWarnings("unchecked")
T[] arrayCopy = (T[]) new Comparable[hi - lo + 1];
System.arraycopy(array, lo, arrayCopy, 0, arrayCopy.length);
int lowIdx = 0;
int highIdx = mid - lo + 1;
for (int i = lo; i <= hi; i++) {
if (lowIdx > mid - lo) {
// left sub array exhausted
array[i] = arrayCopy[highIdx++];
} else if (highIdx > hi - lo) {
// right sub array exhausted
array[i] = arrayCopy[lowIdx++];
} else if (arrayCopy[lowIdx].compareTo(arrayCopy[highIdx]) < 0 == ascend) {
array[i] = arrayCopy[lowIdx++];
} else {
array[i] = arrayCopy[highIdx++];
}
}
}
}),
/**
* 快速排序
* Quick Sorting
*/
QUICK(new Sortable() {
public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {
this.sort(array, 0, array.length - 1, ascend);
}
private <T extends Comparable<T>> void sort(T[] array, int lo, int hi, boolean ascend) {
if (lo >= hi) {
return;
}
// int partitionIdx = partition(array, lo, hi, ascend);
T toFinal = array[lo];
int leftIdx = lo;
int rightIdx = hi;
int i = lo + 1;
while (i <= rightIdx) {
int compare = array[i].compareTo(toFinal);
if (compare == 0) {
i++;
} else if (compare < 0 == ascend) {
exchange(array, leftIdx++, i++);
} else {
exchange(array, rightIdx--, i);
}
}
// partially sort left array and right array
// no need to include the leftIdx-th to rightIdx-th elements
// since they are already in its final position
sort(array, lo, leftIdx - 1, ascend);
sort(array, rightIdx + 1, hi, ascend);
}
/**
* This is the old two-way partition method.
*
* @param array
* @param lo
* @param hi
* @param ascend
* @return partitionIdx
*/
@Deprecated
@SuppressWarnings("unused")
private <T extends Comparable<T>> int partition(T[] array, int lo, int hi, boolean ascend) {
int leftIdx = lo;
int rightIdx = hi + 1;
T toFinal = array[lo];
while (true) {
// search from left to right to locate the element placed
// in the wrong position which should be in the right
while (array[++leftIdx].compareTo(toFinal) < 0 == ascend) {
if (leftIdx >= hi) {
break;
}
}
// search from right to left to locate the element placed
// in the wrong position which should be in the left
while (array[--rightIdx].compareTo(toFinal) > 0 == ascend) {
if (rightIdx <= lo) {
break;
}
}
if (leftIdx >= rightIdx) {
break;
} else {
exchange(array, leftIdx, rightIdx);
}
}
exchange(array, lo, rightIdx);
return rightIdx;
}
}),
/**
*
* 堆排序
* Heap Sorting
*/
HEAP(new Sortable() {
public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {
final int length = array.length;
// Heap use array and below convention to form data. assume k is the
// k-th node then the node with index that nearest to (k - 1) / 2 is
// its
// parent and nodes with 2 * k + 1 and 2 * k + 2 are its two
// children
// initialize a heap
for (int k = (length - 2) / 2; k >= 0; k--) {
sink(array, k, length, ascend);
}
for (int currentHeapSize = length; currentHeapSize > 0;) {
exchange(array, 0, currentHeapSize - 1);
sink(array, 0, --currentHeapSize, ascend);
}
}
private <T extends Comparable<T>> void sink(T[] array, int nodeIdx, int heapSize, boolean ascend) {
while (2 * nodeIdx + 1 < heapSize) {
int childIdx = 2 * nodeIdx + 1;
// find the larger one between its two children, if there is any
if (childIdx + 1 < heapSize) {
int childrenCompare = array[childIdx].compareTo(array[childIdx + 1]);
if (childrenCompare != 0 && childrenCompare < 0 == ascend) {
childIdx++;
}
}
int parentChildCompare = array[nodeIdx].compareTo(array[childIdx]);
if (parentChildCompare == 0 || parentChildCompare > 0 == ascend) {
break;
}
exchange(array, nodeIdx, childIdx);
nodeIdx = childIdx;
}
}
})
;
private SortType(Sortable sortAlgo) {
this.sortAlgo = sortAlgo;
}
private Sortable sortAlgo;
public <T extends Comparable<T>> void sort(T[] array) {
sortAlgo.sort(array, true);
}
public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {
if (array == null || array.length <= 2) {
return;
}
sortAlgo.sort(array, ascend);
}
/**
* exchange the nodes specified by given indices, if the indices are equal,
* do nothing
*
* @param array
* array which hold the elements
* @param p
* one index to exchange
* @param q
* the other index to exchange
*/
private static void exchange(Object[] array, int p, int q) {
if (p == q) {
return;
}
Object temp = array[p];
array[p] = array[q];
array[q] = temp;
}
}
package org.sg.sgg.sort;
public interface Sortable {
/**
* Sort the given array which consists of child class of {@link Comparable}<br/>
*
* @param array
* @param ascend
* if true, using ascend, else using descend
*/
<T extends Comparable<T>> void sort(T[] array, boolean ascend);
}
package org.sg.sgg.sort;
import java.util.Arrays;
import java.util.Random;
import junit.framework.Assert;
import org.junit.Test;
public class SortingTest {
// define the array's size
private final int PROBLEM_SCALE = 10000;
private boolean checkSorted = true;
private boolean showDebugInfo = false;
@Test
// @Ignore
public void selectionSort() {
sort(SortType.SELECTION);
}
@Test
// @Ignore
public void insertionSort() {
sort(SortType.INSERTION);
}
@Test
// @Ignore
public void bubbleSort() {
sort(SortType.BUBBLE);
}
@Test
// @Ignore
public void shellSort() {
sort(SortType.SHELL);
}
@Test
// @Ignore
public void mergeSort() {
sort(SortType.MERGE);
}
@Test
// @Ignore
public void quickSort() {
sort(SortType.QUICK);
}
@Test
// @Ignore
public void heapSort() {
sort(SortType.HEAP);
}
private void sort(SortType sortType) {
Integer[] array = generateArray(PROBLEM_SCALE);
if (showDebugInfo) {
System.out.println("Before: " + Arrays.toString(array));
}
sortType.sort(array);
if (showDebugInfo) {
System.out.println("After " + sortType.name() + " sort: " + Arrays.toString(array));
}
if (checkSorted) {
Assert.assertTrue(isSorted(array));
}
}
private Integer[] generateArray(int length) {
Random rand = new Random();
Integer[] array = new Integer[length];
for (int i = 0; i < length; i++) {
array[i] = rand.nextInt(length * 4);
}
return array;
}
private <T extends Comparable<T>> boolean isSorted(T[] array) {
if (array == null || array.length <= 2) {
return true;
}
// record the result of last comparison
Boolean lastCompare = null;
for (int i = 1; i < array.length; i++) {
int compareResult = array[i - 1].compareTo(array[i]);
if (lastCompare == null || compareResult == 0) {
if (compareResult != 0) {
lastCompare = compareResult > 0;
}
continue;
}
if (compareResult > 0 != lastCompare) {
return false;
}
}
return true;
}
}
|