java10:复制数组

对于基本数据类型,例如 char a , 我们可以直接用char b=a  进行基本数据类型变量的复制,但是由上一篇我们知道,数组名其实是指向数据元素的一个引用,如如直接用 array list2=list1 是不能达到数组的复制的,他只是将list2也指向了list1指向的内存空间。也成了数组的引用。

In Java, you can use assignment statements to copy primitive data type variables, but not
arrays. Assigning one array variable to another array variable actually copies one reference to
another and makes both variables point to the same memory location.
There are three ways to copy arrays:
■ Use a loop to copy individual elements one by one.
■ Use the static arraycopy method in the System class.
■ Use the  clone method to copy arrays; this will be introduced in Chapter 14,
“Abstract Classes and Interfaces.”

有三种方法实现数组的复制

1) 自己写个循环一个一个元素的复制

2)使用system类的类方法 arraycopy

3)使用clone方法,在后面讲到抽象类时候讲到

方法1使用一个循环例如:

int [] source ={12,45,67,7};

int [] targer=new int[source.lenght];

for(int=0;i<target.length;i++)

target[i]=source[i];

在方法2)中,System.arraycopy(sourceAarry,src_pos, targetArray,tar_pos,length); 参数从左到右分别是 源数组,源数组起始位置,目标数组,目标数组起始位置,复制的长度;但是在使用该方法时候一定要注意,targetarray必须是事先申请好内存的。

The arraycopy method does not allocate memory space for the target array. The target array
must have already been created with its memory space allocated. After the copying takes
place, targetArray and sourceArray have the same content but independent memory
locations.

例子:

public class CopyArray
{
	public static void main(String [] args)
	{
		int [] source={2,3,8,56};
		int [] target=new int[source.length];
		for(int i=0;i<target.length;i++)
		{
			target[i]=source[i];
		}
		for(int i=0;i<target.length;i++)
			System.out.println(target[i]);
		int [] tarCopy=new int[source.length];
		System.arraycopy(source,0,tarCopy,0,source.length);
		for(int i=0;i<tarCopy.length;i++)
			System.out.print(tarCopy[i]+"    ");
		
	}
}

运行如下:


如果我们将上面的int [] tarCopy=new int[source,length]换为 int [] tarCopy;则会出现未初始化的提示:




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值