数组的拷贝
public class Test{
public static void main(String[] args) {
int[] arr1 = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] arr2 = new int[] {10, 20, 30, 40, 50, 60, 70, 80, 90 ,100};
for(int i = 0; i < 10; i++) {
System.out.print(arr1[i] + " ");
}
System.out.println();
for (int i = 0; i < arr2.length; i++) {
System.out.print(arr2[i] + " ");
}
System.out.println();
System.arraycopy(arr1, 2, arr2, 5, 3);
for(int i = 0; i < 10; i++) {
System.out.print(arr1[i] + " ");
}
System.out.println();
for (int i = 0; i < arr2.length; i++) {
System.out.print(arr2[i] + " ");
}
System.out.println();
}
}
输出结果:
1 2 3 4 5 6 7 8 9 10
10 20 30 40 50 60 70 80 90 100
1 2 3 4 5 6 7 8 9 10
10 20 30 40 50 3 4 5 90 100
System.arraycopy(src, srcPos, dest, destPos, length);
将指定源数组中的数组从指定位置复制到目标数组的指定位置。 数组的一个子序列被从通过引用的源数组复制src
被引用的目标数组dest
。 复制的元素数量等于length
参数。 源数组中位置srcPos
至srcPos+length-1
的元素分别复制到目标数组的位置destPos
至destPos+length-1
。
jdk底层提供了这样一个数组拷贝的方法,native表示本地方法。
源码中并没有实现的代码:
数组中删除某个元素
本质上还是数组的拷贝,把后面的元素一个个拷贝到前面来。
例子:删除数组s1中第3个元素“cc”:
public class Test{
public static void main(String[] args) {
teseDelete();
}
public static void teseDelete() {
String[] s1 = {"aa", "bb", "cc", "dd", "ee"};
System.arraycopy(s1, 3, s1, 3-1, s1.length-3);
for (int i = 0; i < s1.length; i++) {
System.out.println(i+"--"+s1[i]);
}
}
}
输出结果:
0--aa
1--bb
2--dd
3--ee
4--ee
所以从数组中间删减元素的效率很低。
上面代码还可以再优化一下,让没有的元素变成null,在arraycopy语句下一行跟上:
s1[s1.length - 1] = null;
这样,输出结果就会变成:
0--aa
1--bb
2--dd
3--ee
4--null
封装一个删除数组元素的方法
public class Test{
public static void main(String[] args) {
String[] str = {"土豆", "金针菇", "鱼豆腐", "米饭"};
removeElement(str, 1);
}
public static void removeElement(String[] s, int index){
System.arraycopy(s, index+1, s, index, s.length-index-1);
s[s.length-1] = null;
for (int i = 0; i < s.length; i++) {
System.out.println(i+"--"+s[i]);
}
}
}
输出结果:
0--土豆
1--鱼豆腐
2--米饭
3--null
于是,“金针菇”就这样被吃掉了,哈哈。
数组扩容操作
public class Test{
public static void main(String[] args) {
String[] str = {"土豆", "金针菇", "鱼豆腐", "米饭"};
str = extendRange(str);
}
public static String[] extendRange(String[] s1) {
String[] s2 = new String[s1.length + 10];
System.arraycopy(s1, 0, s2, 0, s1.length);
for (String str : s2) {
System.out.println(str);
}
return s2;
}
}
输出结果:
土豆
金针菇
鱼豆腐
米饭
null
null
null
null
null
null
null
null
null
null