Java刚学到数组拷贝,数组中元素的删减和插入实质全是数组的拷贝,其中主要方法是public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos, int length);
public class ArrayCopy {
public static void main(String[] args) {
String[] str= {"wjl","hwc","lxl","sh"};
RemoveElment(str,2);
InsertElment(str,0,"hdx");
}
public static void BasicsCopy() {
String[] s1= {"a","b","c","d","e","f"};
String[] s2=new String[10];
//实现数组中元素的删除,本质上还是数组的拷贝
System.arraycopy(s1, 3, s1, 2, s1.length-3);
s1[s1.length-1]=null;//数组删减时效率低
System.arraycopy(s1, 1, s2, 3, 4);//源数组,源起始位置,目标数组,目标数组起始位置,拷贝的长度
for(int i = 0;i < 10;i ++) {
System.out.println(i +"--" + s1[i]);
}
}
//还可把删除数组中的一个元素进行封装,返回原数组
public static String[] RemoveElment(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 < 10;i ++) {
System.out.println(i +"--" +s[i]);
}
return s;
}
//数组扩容:本质还是拷贝
public static String[] ExtendRange(String[] s) {
String[] s1=new String[s.length+10];
System.arraycopy(s,0,s1,0,s.length);
return s1;
}
//插入一个元素,先是定义一个新数组并扩容最后两次拷贝加插入一个元素即可
public static String[] InsertElment(String[] s,int index,String str1) {
String[] s1=new String[s.length+10];
System.arraycopy(s,0 , s1,0 , index);
s1[index]=str1;
System.arraycopy(s, index, s1, index+1, s.length-index);
for(String temp:s1) {
System.out.println(temp);
}
return s1;
}
}