package zuoye;
import java.util.*;
/**
* 数组的拷贝
* @author 110
* system类里也包含了一个static void arraycopy(object src,int srcps,object dest,
* int destpos,int length)方法,该方法可以将src数组里的元素值赋给dest数组的元素,其中srcpos指定
* 从src数组的第几个元素开始赋值,length参数指定将src数组的多少个元素赋给dest数组的元素。
*/
public class practice16 {
public static void main(String[] args) {
practice16 p = new practice16();
p.testcopy();
p.testcopy2();
p.extendRange();
}
//单纯的数组拷贝
public static void testcopy() {
String[] s1 = {"aa","bb","cc","dd","ee"};
String[] s2 = new String[10];
System.arraycopy(s1, 2, s2, 6, 3);
for(int i=0;i<s2.length;i++) {
System.out.println(i+" -- "+s2[i]);
}
}
//测试从数组中删除某个元素(本质上还是数组的拷贝)删除“cc”
public static void testcopy2() {
String[] s1 = {"aa","bb","cc","dd","ee"};
String[] s2 = new String[5];
System.arraycopy(s1, 3, s1,3-1,s1.length-3);
s1[s1.length-1]=null;
for(int i=0;i<s2.length;i++) {
System.out.println(i+" -- "+s1[i]);
}
}
//测试给数组中加入某个元素(牵扯到数组的扩容)本质上是先定义一个更大的数组,
//然后将原数组内容原封不动的拷贝到新数组中;
public static void extendRange() {
String[] str1 = {"aa","bb","dd","ee","ff"};
String[] str2 = new String[str1.length+1];
System.arraycopy(str1, 0, str2, 0, str1.length);//将str1中所有元素拷贝到str2中。
System.arraycopy(str2,2 , str2, 3, str2.length-3);
str2[2]="cc";
for(int i = 0;i<str2.length;i++) {
System.out.println(i+"--"+str2[i]);
}
}
}
数组的拷贝
最新推荐文章于 2022-06-12 19:33:23 发布