数组的复制

 数组复制有以下几种方法:

  1. 通过for循环进行数值复制
  2. 源数组名.clone()
  3. public static native void arraycopy(Object src,  int  srcPos,Object dest, int destPo, int length);(System类方法)
  4.  public static int[] copyOf(int[] original, int newLength)   (Arrays类方法)
  5.  public static int[] copyOfRange(int[] original, int from, int to)  (Arrays类方法)

示例代码

package array;

import java.util.Arrays;

public class arrayCopy {

	/**
	 * @jeasion Array Copy 
	 */
	public static void main(String[] args) {
		int[] a= new int[10];
		int[] b= new int[5];
		for(int i=0;i<10;i++){
			a[i]=(int)(Math.random()*10+1);
		}
		for(int j:a){
			System.out.print("\t@a:"+j);
		}
		System.out.println("\n赋值");
		//@1 数组赋值
		for(int i=3;i<8;i++){
			b[i-3]=a[i];
			
		}
		for(int j:b){
			System.out.print("\t@1:"+j);
		}
		System.out.println("\nclone()");
		
		//@2 数组克隆 array.clone()
		b=a.clone();
		for(int j:b){
			System.out.print("\t@2:"+j);
		}
		System.out.println("\nSystem.arraycopy()");
		
		//@3 System.arraycopy(source,first,aim,index,length);
		System.arraycopy(a,3,b,0,5);
		for(int j:b){
			System.out.print("\t@3:"+j);
		}
		System.out.println("\nArraycopyOf()");
		
	//@4 Arrays.copyOf(source,length) --Of  为大写  length是新數組的長度,可以比原數組長

        //Arrays。copyOf(source,source。length+mount) 可以實現原數組長度的擴充


		b=Arrays.copyOf(a, 5);
		for(int j:b){
			System.out.print("\t@4:"+j);
		}
		System.out.println("\nArray.copyRanger()");
		//@5 Arrays.copyRange();
		b=Arrays.copyOfRange(a, 3, 7);
		for(int j:b){
			System.out.print("\t@5:"+j);
		}
	}

}


示例结果

	@a:1	@a:10	@a:8	@a:3	@a:2	@a:8	@a:10	@a:8	@a:3	@a:2
赋值
	@1:3	@1:2	@1:8	@1:10	@1:8
clone()
	@2:1	@2:10	@2:8	@2:3	@2:2	@2:8	@2:10	@2:8	@2:3	@2:2
System.arraycopy()
	@3:3	@3:2	@3:8	@3:10	@3:8	@3:8	@3:10	@3:8	@3:3	@3:2
ArraycopyOf()
	@4:1	@4:10	@4:8	@4:3	@4:2
Array.copyRanger()
	@5:3	@5:2	@5:8	@5:10

 

全部评论

相关推荐

投递腾讯等公司10个岗位
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务