Java 数组拷贝_数组中删除某个元素_数组扩容操作 尚学堂107

 数组的拷贝

public class Test{
	public static void main(String[] args) {
		int[] arr1 = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
		int[] arr2 = new int[] {10, 20, 30, 40, 50, 60, 70, 80, 90 ,100};
		for(int i = 0; i < 10; i++) {
			System.out.print(arr1[i] + " ");
		}
		System.out.println();
		for (int i = 0; i < arr2.length; i++) {
			System.out.print(arr2[i] + " ");
		}
		System.out.println();
		System.arraycopy(arr1, 2, arr2, 5, 3);
		for(int i = 0; i < 10; i++) {
			System.out.print(arr1[i] + " ");
		}
		System.out.println();
		for (int i = 0; i < arr2.length; i++) {
			System.out.print(arr2[i] + " ");
		}
		System.out.println();
	}
}

输出结果:

1 2 3 4 5 6 7 8 9 10 
10 20 30 40 50 60 70 80 90 100 
1 2 3 4 5 6 7 8 9 10 
10 20 30 40 50 3 4 5 90 100 

 System.arraycopy(src, srcPos, dest, destPos, length);

将指定源数组中的数组从指定位置复制到目标数组的指定位置。 数组的一个子序列被从通过引用的源数组复制src被引用的目标数组dest 。 复制的元素数量等于length参数。 源数组中位置srcPossrcPos+length-1的元素分别复制到目标数组的位置destPosdestPos+length-1

 

jdk底层提供了这样一个数组拷贝的方法,native表示本地方法。

源码中并没有实现的代码:

 

 数组中删除某个元素

本质上还是数组的拷贝,把后面的元素一个个拷贝到前面来。

例子:删除数组s1中第3个元素“cc”:

public class Test{
	public static void main(String[] args) {
		teseDelete();
	}
	
	public static void teseDelete() {
		String[] s1 = {"aa", "bb", "cc", "dd", "ee"};
		System.arraycopy(s1, 3, s1, 3-1, s1.length-3);
		for (int i = 0; i < s1.length; i++) {
			System.out.println(i+"--"+s1[i]);
		}
	}
}

输出结果:

0--aa
1--bb
2--dd
3--ee
4--ee 

所以从数组中间删减元素的效率很低。

上面代码还可以再优化一下,让没有的元素变成null,在arraycopy语句下一行跟上:

s1[s1.length - 1] = null;

 这样,输出结果就会变成:

0--aa
1--bb
2--dd
3--ee
4--null

 封装一个删除数组元素的方法

public class Test{
	public static void main(String[] args) {
		String[] str = {"土豆", "金针菇", "鱼豆腐", "米饭"};
		removeElement(str, 1);
	}
	
	public static void removeElement(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 < s.length; i++) {
			System.out.println(i+"--"+s[i]);
		}
	}
}

输出结果:

0--土豆
1--鱼豆腐
2--米饭
3--null

于是,“金针菇”就这样被吃掉了,哈哈。

 数组扩容操作

public class Test{
	public static void main(String[] args) {
		String[] str = {"土豆", "金针菇", "鱼豆腐", "米饭"};
		str = extendRange(str);
	}
	
	public static String[] extendRange(String[] s1) {
		String[] s2 = new String[s1.length + 10];
		System.arraycopy(s1, 0, s2, 0, s1.length);
		for (String str : s2) {
			System.out.println(str);
		}
		return s2;
	}
}

输出结果:

土豆
金针菇
鱼豆腐
米饭
null
null
null
null
null
null
null
null
null
null

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值