The difference between system.arraycopy () and arrays.copyof () in Java-java

Source: Internet
Author: User

If we want to copy an array, we may use either system.arraycopy () or arrays.copyof (). Here, we will use a relatively simple example to illustrate the difference between the two.

1. Sample code:

System.arraycopy ()

int [] arr = {1,2,3,4,5intnewint[ Ten  015); // 5 is the length to copy System. out. println (arrays.tostring (copied));

Operation Result:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 1, 2, 3, 4, 5, 0, 0, 0, 0]

Arrays.copyof ()

int // The length of the new array  = arrays.copyof (arr, 3); System.out.println (arrays.tostring (copied));

Operation Result:

[1, 2, 3, 4, 5, 0, 0, 0, 0, 0] [1, 2, 3]

2. The main difference between the two

The difference is that arrays.copyof () is not just a copy of an element in an array, but a new array object is created when the element is copied. Instead, system.arraycopy only copies the array elements that already exist.

If we have seen the source of arrays.copyof (), we will know that the bottom of the method is called the system.arraycopyof () method.

 Public Static int [] copyOf (intint  newlength) {    intnewint[newlength] ;     0, copy, 0, Math.min (Original.length, newlength));     return copy;}

The difference between system.arraycopy () and arrays.copyof () in Java-java

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.