Four methods to copy an array in Java

Arrays类:copyOf()、copyOfRange()

System类:arraycopy()

Object class: clone ()

一、public static int[] copyOf(int[] original, int newLength)

Generating a new array, a new array of arbitrary length, it may be newLength:

1. larger than the original array

Later, when a new array is greater than the original length of the array, a new array has copied the original array back up defaults

2. less than the original array

Copy of the original array before newLength items

3. 0

Generating a same type of empty array, a length of 0

int[] nums = {-10, -3, 1, 5, 9};
int[] nums1= Arrays.copyOf(nums, 0);

二、public static T[] copyOfRange(T[] original, int from, int to)

Generating a new array of any length, the new array. And python in the same range, it includes left and right is not included.

1. equal right border left border

It returns an empty array of the original array type, length 0

2. The original length of the array is greater than the right border

After completion of copying the original data array back up defaults

3.0<=from<to<=original.length

三、public static native void arraycopy(Object src, int srcPos,Object dest, int destPos, int length);

Because it is replicated between two existing arrays, and called for strict parameters, not out of range.
+ length srcPos <= src.length
destPos + length <= src.length

int[] nums = {1,2,3,4,5,6};
int[] nums1= {6,7,8,9,0};
System.arraycopy(nums,2,nums1,2,2);

Four, clone ()

clone object class method, using a new piece of the original copy of the memory array to generate a new array, before the new array may be present, such as nums1, may not exist as nums2

public class Test {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5, 6};
        int[] nums1 = {9, 8, 7};
        System.out.println(nums1.length);//3
        nums1 = nums.clone();
        System.out.println(nums1.length);//6
        System.out.println(nums == nums1);//false
        System.out.println(nums.equals(nums1));//false
        for (int i = 0; i < nums1.length; i++) {
            System.out.print(nums1[i] + " ");//1 2 3 4 5 6 
        }
        System.out.println();
        int[] nums2 = nums.clone();
        System.out.println(nums1 == nums2);//false
        System.out.println(nums1.equals(nums2));//false
        nums1 = nums;
        System.out.println(nums1 == nums);//true
        System.out.println(nums1.equals(nums));//true
    }
}
发布了12 篇原创文章 · 获赞 5 · 访问量 948

Guess you like

Origin blog.csdn.net/Seventeen0084/article/details/99689977