How to copy an array in java

Source: Internet
Author: User

In JAVA, you can use the copy statement "A = B" to pass values to basic data types. However, if A and B are arrays of the same type, copying is equivalent to passing an array variable reference to another array. If an array changes, the variables that reference the same Array also change.

The following describes how to copy an array in JAVA:
1. Use the FOR loop to copy or copy each element of the array, but the efficiency is poor.
2. Use the clone method to obtain the value of the array, instead of reference. You cannot copy the specified element, which is less flexible.
3. We recommend that you use the System. arraycopy (src, srcPos, dest, destPos, length) method.

Example:
1. Use the FOR Loop
Don't talk about it.

2. Use clone
Int [] src = {1, 3, 5, 6, 7, 8 };
Int [] dest;
Dest = (int []) src. clone (); // create with clone
Copy. Note that forced conversion is required for clone.

3. 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.