今天,阿桂问我,数组怎么删除元素?
什么?你又钻什么牛角尖,好好的list不用。
一物不知,深以为耻。
好吧,我也钻一下。上代码。
public class Arraytest {
public static void main(String[] args) {
Integer[] i = {1,2,3,4,5,6,7};
Object[] remove = remove(i, 1);
for (int j = 0; j < remove.length; j++) {
System.out.print(remove[j]);
}
}
private static Object[] remove(Object[] src,int index) {
int size = src.length; //
int numMoved = size - index - 1;//计算预删除元素右边的元素个数
Object[] desc = Arrays.copyOf(src, size - 1);//复制成新数组,去掉尾部元素
System.arraycopy(src, index+1, desc, index, numMoved);//复制的起始位置确定好,将源数组的右边的元素贴到新数组中。
return desc;//返回新数组
}
}
运行结果:134567
java中 数组是典型的线性表结构。移除元素,后面的所有元素都要前移一位。
我这里用了两次copy才做到了remove操作。
ArrayList 提供的 remove 只需要copy一次,原因是遍历的时候,集合用的是size方法,而数组直接使用length属性。
当然遍历的时候remove要记得用迭代器。