直接让两个数组相等的结果:两个数组指向同一内存位置,实现了数组引用的赋值。
使用静态方法arraycopy的结果:实现数组值的复制。
举个栗子:
public class Assignment
{
public static void main(String args[])
{
int i;
int [] first = {1, 2, 3, 4};
int second[] = {5, 6, 7};
int third[] = {5, 6, 7}; // second 与 third 为两个相同的数组。
second = first; // 第一种方法:直接赋值
System.arraycopy(first, 0, third, 0, 2); // 第二种方法:使用函数
System.out.print("first : ");
for (i=0; i<first.length; i++)
System.out.print(" " + first[i]);
System.out.print("\nsecond : ");
for (i=0; i<second.length; i++)
System.out.print(" " + second[i]); // 输出第一种赋值的结果
System.out.print("\nthird : ");
for (i=0; i<third.length; i++)
System.out.print(" " + third[i]); // 输出第二种赋值的结果
}
}
运行结果:
first : 1 2 3 4
second : 1 2 3 4 // second 与 first完全一致
third : 1 2 7 // third 在指定位置做了复制替换
附上arraycopy的函数原型:
public static void arraycopy(Object src, => 源数组
int srcPos, => 源数组复制的起始位置
Object destPos, => 目的数组
int destPos, => 目的数组粘贴的起始位置
int length) => 粘贴复制的长度
// src 和 dest 必须是同类型或者可以进行类型转换的数组.