因此,sort方法的for循环中,当i=0时array[array.length-i]等于array[array.length]下标越界,把sort方法的for循环中的两个array[array.length-i]改成array[array.length-1-i]就行了.
import java.util.*import java.lang.*
public class demo {
public static void main(String args[]) throws Exception{
int[] arr={1,2,3,4,5,6}
arr=remove(arr,2)// 移除下标为2的元素
for(int x:arr) System.out.println("x="+x)// 移除后数组剩下的元素
}
// 移除数组指定下标的元素 重载+1
private static int[] remove(int[] array,int index){
return (int[]) remove((Object) array, index)
}
// 移除数组指定下标的元素 重载+2
private static Object remove(Object array,int index){
int length = java.lang.reflect.Array.getLength(array)
if (index < 0 || index >= length) {
throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length)
}
Object result=java.lang.reflect.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
}
}
数组中的元素在内存是连续排列的,有时我们我处理里面的数据并不是从头取到尾,有时从中间取,所以这里就需要一个下标,标记是在哪个位置,这个下标就就是索引,比如中药铺里面的药柜,要写明药名是不,这个名就是索引.而数组下标是从0开始的.比如a[0],a[1],a[2],a[3],a[4],a[5] 这0,1,2,3,4,5,就是索引