`
JackyCheng2007
  • 浏览: 253795 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Java System 类详解 - arraycopy

    博客分类:
  • Java
阅读更多
System类提供了数组copy函数:
    public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

从参数列表上看,src和dest都是Object,说明可以copy任意数组。那么我们知道数组既可以是原始类型值的数组,也可以是对象类型的数组。如果是原始类型的数组,copy的就是值,如果是对象类型的数字copy的就是对象的引用而非数据。

Copy Primitive Array
package jdk.lang;
import java.util.Arrays;

public class SystemArrayCopy {
	public static void main(String[] args) throws Exception {
		copyPrimitiveArray();
	}

	public static void copyPrimitiveArray() {
		int[] source = new int[] { 1, 2, 3, 4, 5 };
		int length = source.length;
		int[] dest = new int[length];
		System.arraycopy(source, 0, dest, 0, length);
		System.out.println("source: "+Arrays.toString(source));
		System.out.println("dest: "+Arrays.toString(dest));
		for (int i = 0; i < length; i++) {
			source[i] = i + 10;
		}
		System.out.println("source: "+Arrays.toString(source));
		System.out.println("dest: "+Arrays.toString(dest));
		
	}
}


输出:

source: [1, 2, 3, 4, 5]
dest: [1, 2, 3, 4, 5]
source: [10, 11, 12, 13, 14]
dest: [1, 2, 3, 4, 5]


分析:
元数据source在copy之后修改不会对dest数据产生影响。

package jdk.lang;
import java.util.Arrays;

public class SystemArrayCopy {
	public static void main(String[] args) throws Exception { 
		copyReferenceArray();
	} 
	public static void copyReferenceArray() {
		int size = 2;
		Person[] source = new Person[size];
		for (int i = 0; i < size; i++) {
			source[i] = new Person("Persion" + i, i);
		}

		Person[] dest = new Person[size];
		System.arraycopy(source, 0, dest, 0, size);
		System.out.println("source: "+Arrays.toString(source));
		System.out.println("dest: "+Arrays.toString(dest));

		for (int i = 0; i < size; i++) {
			source[i].setAge(10 + i);
			source[i].setName("Persion" + (i + 10));
		}

		System.out.println("source: "+Arrays.toString(source));
		System.out.println("dest: "+Arrays.toString(dest));
	}

	private static class Person {
		private String name;
		private int age;

		public Person(String name, int age) {
			super();
			this.name = name;
			this.age = age;
		}

		public void setName(String name) {
			this.name = name;
		}

		public void setAge(int age) {
			this.age = age;
		}

		public String toString() {
			return String.format("(name, age):(%s, %d) ", name, age);
		}
	}
}
 


输出:

source: [(name, age):(Persion0, 0) , (name, age):(Persion1, 1) ]
dest: [(name, age):(Persion0, 0) , (name, age):(Persion1, 1) ]
source: [(name, age):(Persion10, 10) , (name, age):(Persion11, 11) ]
dest: [(name, age):(Persion10, 10) , (name, age):(Persion11, 11) ]


分析:
元数据source在copy之后修改会对dest数据产生影响。他们hold的是同一组数据的引用。


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics