How to paste a given array into another array at a specified position?

Bài viết này sẽ hướng dẫn cách sử dụng System.arraycopy để sao chép một mảng và dán nó vào một mảng khác với một vị trí được chỉ động trong mảng đó trong ngôn ngữ lập trình Java.

Java Source - Mã Java:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package z_test;

import java.util.Arrays;

/**
 *
 * @author Bui Ngoc Son
 * @website vnlives.net
 * @version 1.0
 * @create 26/11/2014
 */
public class ArrayCopyDemo {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        int[] bigger_array = {0, 0, 0, 0, 0, 0, 0, 0, 0};
        int[] smaller_array = {1, 2, 3};

        // Start copying from position 1 in source, and into
        // position 3 of the destination, and copy 2 elements.
        int srcPos = 1;
        int destPos = 3;
        int length = 2;

        System.arraycopy(smaller_array, srcPos, bigger_array, destPos, length);
        System.out.println("Bigger_array: " + Arrays.toString(bigger_array));

    }
}

Result - Kết Quả:





No comments:

Post a Comment