Methods for copying arrays in Java

Source: Internet
Author: User

In Java, you can use the copy statement "A=b" to pass values to the basic type of data, but if a and B are two arrays of the same type, copying is equivalent to passing a reference to an array variable to another array, and if an array changes, then

Variables referencing the same array are also changed.

Here is a summary of the methods of copying arrays in Java:

1. Use a for loop to copy or copy the specified element for each element of the array, although the efficiency is almost

2. Use the Clone method to get the value of the array, not the reference, cannot copy the specified element, flexibility is almost

3. Use system.arraycopy (src, Srcpos, dest, Destpos, Length) method , recommended

Example:

1. Using A For loop

Int[] src={1,3,5,6,7,8};

int[] Dest = new Int[6];

for (int i=0;i<6;i++) dest[i] = Src[i];

2. Use clone

Int[] src={1,3,5,6,7,8};

Int[] dest;

Dest= (int[]) src.clone ();//Use Clone to create

Copy, note clone to use cast

3. Using System.arraycopy

Int[] src={1,3,5,6,7,8};

int[] Dest = new Int[6];

System.arraycopy (src, 0, dest, 0, 6);
——————————————————————-
System provides a static method Arraycopy (), which we can use to implement replication between arrays.

Its function prototypes are:

public static void Arraycopy (object src, int srcpos, object dest, int destpos, int length)

src: source array;

Srcpos: The starting position of the source array to be copied;

dest: an object array;

Destpos: The starting position of the destination array placement;

Length: The size of the copy.

Note :both SRC and dest must be of the same type or an array of types that can be converted.

The interesting thing is that this function can implement itself to replicate to itself,

Like what:

Int[] Fun ={0,1,2,3,4,5,6};

System.arraycopy (fun,0,fun,3,3);

The result is: {0,1,2,0,1,2,6};

Methods for copying arrays in Java

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.