3.4 数组的拷贝函数

数组的拷贝函数

数组拷贝函数

函数 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);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值