数组的拷贝(System.arraycopy())

package 数组2;

import java.util.Arrays;

/**

  • 测试数组的拷贝
  • @author

*/
public class TestArrayCopy {

public static void main(String[] args) {
	/*int[] a = {1,2,3,4};
	int[] b = new int[10];
	System.arraycopy(a, 1, b, 1, 2);
	for(int i = 0; i<b.length; i++){
		System.out.println(i+"->"+b[i]);}*/

// String[] str = {“aa”,“bb”,“cc”,“dd”};
// removeElment(str,1);
// System.out.println(Arrays.toString(str));
//
// str = extendRange(str);

	int[] a = {1,2,3,5,6};
	a = testBasicCopy2(a, 4, 3);
	System.out.println(Arrays.toString(a));
}



public static void testBasicCopy(){
	int[] a = {1,2,3,4};
	int[] b = new int[10];
	System.arraycopy(a, 1, b, 1, 2);
	
	
	for(int i = 0; i<b.length; i++){
		System.out.println(i+"->"+b[i]);}
}

//测试数组中删除某个元素(本质上还是数组的拷贝)
public static void testBasicCopy1(){
	String[] s1 = {"aa","bb","cc","dd","ee"};
	//String[] s2 = new String[5];
	
	System.arraycopy(s1, 3, s1, 3-1, s1.length-3);
	Arrays.toString(s1);
}

//删除数组中指定索引位置的元素,并将原数组返回
public static String[] removeElment(String[] s,int index){
    //String[] s = {"aa","bb","cc","dd","ee"};
	//String[] s2 = new String[5];
	index +=1;
	System.arraycopy(s, index, s, index-1, s.length-index);
	
	s[s.length-1] = null;
	
	return s;
}

//数组的扩容(本质上是:定义一个更大的数组,然后将原数组内容原封不动拷贝到新数组)
public static String[] extendRange(String[] s1){
	//String[] s1 = {"aa","bb","cc"};
    
	String[] s2 = new String[s1.length+10];
	
	System.arraycopy(s1, 0, s2, 0, s1.length);
	
	for(String i:s2){
		System.out.println(i);
	}
	return s2;
}


//指定位置增加元素
public static int[] testBasicCopy2(int[] m,int a,int b){//a 为所插入元素  b为所插入位置
	int[] s1 = new int[m.length+10];
	int[] s2 = new int[m.length+10];
	
	System.arraycopy(m, 0, s1, 0, b);
	System.arraycopy(m, b, s2, 0, m.length-b);
	s1[b] = a;
	System.arraycopy(s2, 0, s1, 4, m.length);

	return s1;
	
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值