--system.arraycopy method of Java method and arrays.copyof () __java

Source: Internet
Author: User

System.arraycopy method: If the array is larger, then the use of system.arraycopy will be more advantageous, because it uses memory replication, eliminating a large number of array addressing access and other time

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

Copies the specified source array src to the target array dest. copying starts with the Srcpos index of SRC, the number of copies is length, and the index copied to dest begins at Destpos.

1. Basic Use

    @Test public
    void Testcopy () {
        int[] ids = {1, 2, 3, 4, 5};

        1, the test copy to the other array
        //The IDs array index from 0 after 5, copied to the IDS2 array index starting from 0
        int[] ids2 = new Int[5];
        System.arraycopy (IDs, 0, IDS2, 0, 5);
        System.out.println (arrays.tostring (IDS2)); [1, 2, 3, 4, 5]


        //2, test self-replicating
        system.arraycopy (IDs, 0, IDs, 3, 2);
        System.out.println (arrays.tostring (IDs)); [1, 2, 3, 1, 2]


        //3, if it is type conversion problem
        object[] O1 = {1, 2, 3, 4.5, 6.7};
        integer[] O2 = new integer[5];
        try {
            system.arraycopy (O1, 0, O2, 0, o1.length);
        } catch (Arraystoreexception ex) {
            //Storage conversion occurs, Partially successful data is replicated past
            System.out.println ("Copy occurrence exception: Data conversion error, cannot be stored.") ");
        }
        As a result, the previous 3 data that can be copied are already stored. The remainder is not
        System.out.println (arrays.tostring (O2));//[1, 2, 3, NULL, NULL]
    }

2, after the replication of the change after the array

If you are copying a one-dimensional array, changing the copied array does not affect the original array. But if you copy a two-dimensional array, and then change any of these arrays, the value of the other is also changed. The beginning is not very clear, and then the Internet to check the data, understand the mystery.

Java actually does not have two-dimensional array concept, the ordinary implementation of two-dimensional array is only the element is one-dimensional array of one-dimensional array, and the array is also a reference type, inherited from the object class. The array is new. These properties also cause problems when arraycopy () two-dimensional arrays occur.

If it is a one-dimensional array, then the elements are basic types (such as int,double, etc.), using the Arraycopy () method, the value of the original array is passed to the new array, which belongs to the value pass. In the case of a two-dimensional array, the first dimension of the array is a reference to a one-dimensional array, and the second virial is the element value. After applying the Arraycopy () method to a two-dimensional array, the first-dimensional reference is copied to the first dimension of the new array, where the first dimension of the two arrays points to the same "those arrays". The value of the elements of any one of these arrays is changed, and the values of the elements of those arrays are modified, so the original array and the new array have the same element values.

    @Test public void TestCopy2 () {int[] S1 = {1, 2, 3, 4, 5};
        int[] s2 = new INT[5];

        System.arraycopy (S1, 0, S2, 0, 5);
        System.out.println ("This is S1");
        for (int as1:s1) {System.out.print (aS1 + ",");
        } s2[2] = 111;
        System.out.println ("\nthis is S2");
        for (int as2:s2) {System.out.print (aS2 + ",");
        } System.out.println ("\nthis is S1");
        for (int as1:s1) {System.out.print (aS1 + ",");
        } System.out.println ("\ n-----------------------");
        Two-dimensional array int[][] S3 = {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}};
        Int[][] S4 = new Int[s3.length][s3[0].length];
        System.out.println ("This is S3");
        System.arraycopy (S3, 0, S4, 0, S3.length); For (int[] as3:s3) {for (int j = 0; J < S4[0].length; J +) {System.out.print (As3[j] + "
            ,"); }} S4[1][3] = 111;
        System.out.println ("\nthis is S4"); For (int[] as4:s4) {for (int j = 0; J < S4[0].length; J +) {System.out.print (As4[j] + "
            ,");
        } System.out.println ("\nthis is S3"); For (int[] as3:s3) {for (int j = 0; J < S4[0].length; J +) {System.out.print (As3[j] + "
            ,"); }
        }
    }

Result: This is S1:1, 2, 3, 4, 5,
This is s2:1, 2, 111, 4, 5,
This is S1:1, 2, 3, 4, 5,
-----------------------
This is s3:1,2,3,4,5,6,7,8,9,10,
This is s4:1,2,3,4,5,6,7,8,111,10,

This is s3:1,2,3,4,5,6,7,8,111,10, 3, arrays.copyof ()

This method has a corresponding method overload for different data types.

Complex data type public
static <T,U> t[] copyof (u[] original, int newlength, class<? extends t[]> NewType) {
        T [] Copy = ((object) NewType = = (object) object[].class)
            ? (t[]) new Object[newlength]
            : (t[]) array.newinstance (Newtype.getcomponenttype (), newlength);
        System.arraycopy (original, 0, copy, 0,
                         math.min (Original.length, newlength));
        return copy;
    }
public static <T> t[] copyof (t[] original, int newlength) {return
    (t[)) copyof (original, Newlength, original.ge Tclass ());
}
copied by the U type to the T type.
Original-the array to copy
Newlength-The length of the replica to be returned
NewType-type of replica to be returned

  Basic data types (other similar byte,short 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;
    }
Observe its source code Discovery copyof (), create a new array inside it, and then call Arraycopy () to copy the content back out.
Summarize:
The implementation of 1.copyOf () is arraycopy ();
2.arrayCopy () requires a target array to perform a possible incomplete merge of the contents of two arrays.
3. Copyof () Creates a new array internally and invokes Arraycopy () to copy the original content to copy and the length is newlength. return copy;
The 4.arraycopy method is indexoutofboundsexception because the new array size is smaller than the size of the array.
Copyof does not make an error because the return value of copyof is an internal new copy array, and the copy array new is equal to the size of Newlength,
So even after the client has specified the size of the new array NewArray, the return value is also followed by an array copy that points to the bottom new. In other words (you can also make other distinctions), in client code, even if you do not give the new array an object, such as: string[] newstr = null; then for arraycopy it would be nullpointerexception error, For the copyof method in Java.util.Arrays, the error is not reported because the JDK has new objects on the bottom. However, it is necessary to note that the Copyof method is also the last way to call System.arraycopy, but because of the previous preparation, the exception will not appear.


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.