Five ways to copy arrays in JAVA __java

Source: Internet
Author: User
"=" is equivalent to passing a reference to an array variable to another array, and if an array changes, the variable referencing the same array will also change. Use a For loop to copy or copy each element of an array to the specified element, but the efficiency is almost using the Clone method to get the value of the array, rather than the reference, cannot copy the specified element, the flexibility is almost using system.arraycopy (SRC, srcpos, dest, Destpos, length) method, recommended to use, the most efficient


public static native void Arraycopy (object src, int srcpos, object dest, int destpos,int length);
SRC: source array; Srcpos: The starting position to copy the source array;
Dest: Destination array; Destpos: The starting position of the destination array placement;
Length: The size of the copy.

Because according to System.arraycopy () source, you can see is the native method: Native keyword description of its modified method is an original ecological method, the corresponding implementation of the method is not in the current file, but in other languages (such as C and C + +) implementation of the file. You can compare the native method to an interface between a Java program and a C program.

5. Copyof (), not the system method, but the arrays method, the following is the source code, can see essentially is the call arraycopy method. , then its efficiency is necessarily inferior to arraycopy.

public static int[] copyof (int[] original, int newlength) {
   int[] copy = new Int[newlength];
   System.arraycopy (original, 0, copy, 0,
   math.min (Original.length, newlength));
   return copy;
}

How to use:
1. Use clone
Int[] src={1,3,5,6,7,8};
Int[] dest;
Dest= (int[]) src.clone ();//Create a copy using clone, note that clone uses the cast

2. Use System.arraycopy
Int[] src={1,3,5,6,7,8};
int[] Dest = new Int[6];
System.arraycopy (src, 0, dest, 0, 6);

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.