Introduction to Java for beginners 200 examples 64 of several methods of Java copying (copying) arrays

Keywords: Java

Introduction to the author

Author name: Ming Shiyin in programming world
Introduction: CSDN blog expert has been engaged in software development for many years and is proficient in Java and JavaScript. Bloggers also learn and grow step by step from scratch, know the importance of learning and accumulation, and like to fight and upgrade with ADC. Welcome to pay attention and look forward to learning, growing and taking off with you!

introduction

Many Java beginners ask me that it's worrying for the novice to turn around and forget the Java knowledge he has studied very hard. How can Xiaobai grow up quickly and become a big cow?
In fact, there is only one skill to become a big God: "learn more and practice more", so brother Ming sorted out typical practice examples. Through practice, you can quickly improve coding skills and proficiency, so that you can never return on the way to become a big man (remember to practice with your own hands)!

Navigation

✪ introduction to Java white 200 case series directory index
◄ previous article    63. Judge whether the arrays are equal (array comparison)
► next    65.Java sort() array sorting

describe

Copying an array refers to copying elements in one array into another.

Method 1

Use the copyOf() method to copy the array
The syntax format of the copyOf() method of the Arrays class is as follows:

Arrays.copyOf(dataType[] srcArray,int length);

Where srcrarray represents the array to be copied, and length represents the length of the new array after copying.

package demo.demo64;

import java.util.Arrays;

public class Clone1 {

	public static void main(String[] args) {
		  // Define array
        int arr1[] = new int[]{57,81,68,75,91};
        // Output original array
        System.out.println("The contents of the original array are as follows:");
        // Loop through the original array
        for(int i=0;i<arr1.length;i++) {
            // Output array elements
            System.out.print(arr1[i]+"\t");
        }
        // Define a new array and copy the elements in the arr1 array
        // At the same time, 3 memory spaces are reserved for future development
        int[] arr2 = (int[])Arrays.copyOf(arr1,8);
        System.out.println("\n The contents of the copied new array are as follows:");
        // Loop through the copied new array
        for(int j=0;j<arr2.length;j++) {
            // Output the elements of the new array
            System.out.print(arr2[j]+"\t");
        }
        
        // Define a new array and copy the elements in the arr1 array, as long as four elements
        int[] arr3 = (int[])Arrays.copyOf(arr1,4);
        System.out.println("\n The contents of the copied new array are as follows:");
        // Loop through the copied new array
        for(int j=0;j<arr3.length;j++) {
            // Output the elements of the new array
            System.out.print(arr3[j]+"\t");
        }
	}

}

Operation results:

The contents of the original array are as follows:
57 81 68 75 91
The contents of the copied new array are as follows:
57 81 68 75 91 0 0 0
The contents of the copied new array are as follows:
57 81 68 75

Method 2

Use the CopyOfRange() method to copy the array
CopyOfRange() method of Arrays class is another method to copy Arrays. Its syntax is as follows:

Arrays.copyOfRange(dataType[] srcArray,int startIndex,int endIndex)

Of which:
Srcrarray represents the original array.
startIndex indicates the starting index to start copying. The target array will contain the elements corresponding to the starting index. In addition, startIndex must be between 0 and srcrarray.length.
endIndex means to terminate the index. The target array will not contain the element corresponding to the terminated index. endIndex must be greater than or equal to startIndex, which can be greater than srcraray.length. If it is greater than srcraray.length, the target array will be filled with the default value.

package demo.demo64;

import java.util.Arrays;

public class Clone2 {

	public static void main(String[] args) {
		  // Define array
        int arr1[] = new int[]{57,81,68,75,91};
        // Output original array
        System.out.println("The contents of the original array are as follows:");
        // Loop through the original array
        for(int i=0;i<arr1.length;i++) {
            // Output array elements
            System.out.print(arr1[i]+"\t");
        }
        // Define a new array and copy the elements in the arr1 array
        // Starting from 0, if there are only 5 in total, 3 positions will be filled by default
        int[] arr2 = (int[])Arrays.copyOfRange(arr1,0,8);
        System.out.println("\n The contents of the copied new array are as follows:");
        // Loop through the copied new array
        for(int j=0;j<arr2.length;j++) {
            // Output the elements of the new array
            System.out.print(arr2[j]+"\t");
        }
        
        // Define a new array and copy the elements in the arr1 array, as long as the elements 2 and 3
        int[] arr3 = (int[])Arrays.copyOfRange(arr1,2,4);
        System.out.println("\n The contents of the copied new array are as follows:");
        // Loop through the copied new array
        for(int j=0;j<arr3.length;j++) {
            // Output the elements of the new array
            System.out.print(arr3[j]+"\t");
        }
	}

}

Operation results:
The contents of the original array are as follows:
57 81 68 75 91
The contents of the copied new array are as follows:
57 81 68 75 91 0 0 0
The contents of the copied new array are as follows:
68 75

Method 3

Use clone() method
The clone() method can also copy arrays. This method is a method in class Object, which can create an Object with separate memory space. Because the array is also an Object class, you can also use the clone() method of the array Object to copy the array.

The return value of the clone() method is the Object type, which should be cast to the appropriate type. Its grammatical form is relatively simple:

array_name.clone()

package demo.demo64;

import java.util.Arrays;

public class Clone3 {

	public static void main(String[] args) {
		  // Define array
        int arr1[] = new int[]{57,81,68,75,91};
        // Output original array
        System.out.println("The contents of the original array are as follows:");
        // Loop through the original array
        for(int i=0;i<arr1.length;i++) {
            // Output array elements
            System.out.print(arr1[i]+"\t");
        }
        // Define a new array and copy the elements in the arr1 array
        int[] arr2 = (int[])arr1.clone();
        System.out.println("\n The contents of the copied new array are as follows:");
        // Loop through the copied new array
        for(int j=0;j<arr2.length;j++) {
            // Output the elements of the new array
            System.out.print(arr2[j]+"\t");
        }
	}

}

Operation results:

The contents of the original array are as follows:
57 81 68 75 91
The contents of the copied new array are as follows:
57 81 68 75 91

Method 4

Encapsulate the method to copy. Of course, this method defines the int array. If you want to copy other arrays, you need to redefine them.

package demo.demo64;

public class Clone4 {

	public static void main(String[] args) {
		  // Define array
        int arr1[] = new int[]{100,66,37,25,77};
        // Output original array
        System.out.println("The contents of the original array are as follows:");
        // Loop through the original array
        for(int i=0;i<arr1.length;i++) {
            // Output array elements
            System.out.print(arr1[i]+"\t");
        }
        // Define a new array and copy the elements in the arr1 array
        int[] arr2 = doClone(arr1);
        System.out.println("\n The contents of the copied new array are as follows:");
        // Loop through the copied new array
        for(int j=0;j<arr2.length;j++) {
            // Output the elements of the new array
            System.out.print(arr2[j]+"\t");
        }
	}
	
	
	private static int[] doClone(int[] o){
		int[] res = new int[o.length];
		for (int i = 0; i < o.length; i++) {
			res[i]=o[i];
		}
		return res;
	}
}

function:

The contents of the original array are as follows:
100 66 37 25 77
The contents of the copied new array are as follows:
100 66 37 25 77

Method 5

Encapsulate the method with start subscript and end subscript

package demo.demo64;

public class Clone4 {

	public static void main(String[] args) {
		  // Define array
        int arr1[] = new int[]{100,66,37,25,77};
        // Output original array
        System.out.println("The contents of the original array are as follows:");
        // Loop through the original array
        for(int i=0;i<arr1.length;i++) {
            // Output array elements
            System.out.print(arr1[i]+"\t");
        }
        // Define a new array and copy the elements in the arr1 array
        int[] arr2 = doClone(arr1,1,9);
        System.out.println("\n The contents of the copied new array are as follows:");
        // Loop through the copied new array
        for(int j=0;j<arr2.length;j++) {
            // Output the elements of the new array
            System.out.print(arr2[j]+"\t");
        }
	}
	
	//Self defined copy with subscript
	private static int[] doClone(int[] o,int start,int end){
		if(start<0){//If the starting subscript is less than 0, make it equal to 0
			start=0;
		}
		//If the start subscript is greater than the length of the original array, an empty array is returned
		if(start>o.length){
			return new int[0];
		}
		//If the start is greater than the end, the end is set to the array length
		if(start>end){
			end = o.length;
		}
		int[] res = new int[end-start];
		int n=0;
		for (int i = start; i < end; i++) {
			if(i>=o.length){//If the array boundary has been exceeded, exit
				break;
			}
			res[n++]=o[i];
		}
		return res;
	}
}

Operation results:

The contents of the original array are as follows:
100 66 37 25 77
The contents of the copied new array are as follows:
66 37 25 77 0 0 0 0

Of course, only int arrays are encapsulated here. If you want to operate on other types of arrays, you need to re encapsulate the method. The principle is similar and can be modified slightly.

Summary

This section summarizes "several methods of Java copying (copying) arrays", hoping to be helpful to you. Please help [like] + [collection] + [punch in the comment area]. If you are interested in learning java with brother Xiaoming, [pay attention to a wave] won't get lost.

Let me know you by punching in the comment area. Mingge will continue to pay attention to your learning progress!

Navigation

✪ introduction to Java white 200 case series directory index
◄ previous article    63. Judge whether the arrays are equal (array comparison)
► next    65.Java sort() array sorting

Popular column recommendation

1.Java game series (Tetris, aircraft war, plant war, zombie, etc.)
2.JavaWeb project practice (library management, online examination, dormitory management system, etc.)
3. Wonderful examples of JavaScript (aircraft war, minesweeping, snake eating, verification code, etc.)
4. Introduction to Java Xiaobai 200 cases
5. Learn Java from zero, learn Java with interest, and learn Java from the perspective of King glory

Posted by ivalea on Fri, 24 Sep 2021 18:03:05 -0700