数组拷贝函数
函数 arraycopy(src, srcPos, dest, destPos, length)
- src the source array.
- srcPos starting position in the source array.
- dest the destination array.
- destPos starting position in the destination data.
- length the number of array elements to be copied.
调用方法:System.arraycopy(src, srcPos, dest, destPos, length)
拓展
利用数组拷贝方法实现简易的数组删除元素,数组扩容,向数组中插入元素这三个功能。
/**
* 利用数组拷贝,实现数组删除元素,数组扩容,向数组中插入元素
* @author dxt
*
*/
public class TestArrayCopy2 {
/**
* 删除数组s中索引为index的元素
* @param s
* @param index
* @return
*/
public String[] removeElement(String[] s, int index){
System.arraycopy(s, index+1, s, index, s.length-index-1);
s[s.length-1] = null;
return s;
}
/**
* 扩展数组的长度
* @param s
* @return
*/
public String[] extendRange(String[] s){
String[] str = new String[s.length*2];
System.arraycopy(s, 0, str, 0, s.length);
return str;
}
/**
* 将str插入到数组s的索引为index的位置处
* @param s
* @param index
* @param str
* @return
*/
public String[] insertElement(String[] s, int index, String str){
//判断索引是否越界.....略
//判断数组是否已满.....略
String[] s2 = new String[s.length + 1];
System.arraycopy(s, 0, s2, 0, index);
s2[index] = str;
System.arraycopy(s, index, s2, index+1, s.length-index);
return s2;
}
/**
* 输出数组s
* @param s
*/
public void output(String[] s){
for(int i=0; i<s.length; i++){
System.out.println(i + "----" + s[i]);
}
}
public static void main(String[] args){
String[] s = {"aa", "bb", "cc", "dd", "ee"};
String[] s1 = {"aa", "bb", "cc", "dd", "ee"};
TestArrayCopy2 tac2 = new TestArrayCopy2();
s1 = tac2.removeElement(s1, 0);
tac2.output(s1);
s1 = s;
s1 = tac2.extendRange(s1);
tac2.output(s1);
s1 = s;
s1 = tac2.insertElement(s1, s1.length-1, "zz");
tac2.output(s1);
}
}