Sao chép các phần tử của một mảng sang mảng khác như thế nào?

Chúng ta hãy xem xét chương trình sau đây:

package com.maixuanviet.arrays;

public class CopyArrayExample1 {
public static void main(String[] args) {

int[] a = { 12, 21, 0, 5, 7 }; // Declaring and initializing an array of ints

int[] b = a; // copying array ‘a’ to array ‘b’

// Printing elements of array ‘b’
for (int i = 0; i < b.length; i++) { System.out.println(b[i]); } a[2] = 56; // Changing value of 3rd element of array 'a' System.out.println(b[2]); // value of 3rd element of array 'b' also changes = 56 b[4] = 100; // Changing value of 5th element of array 'b' System.out.println(a[4]); // value of 5th element of array 'a' also changes = 100 } } [/code]

Trong ví dụ trên, chúng ta đang khai báo một mảng kiểu int. Chúng ta sao chép mảng đó sang mảng khác kiểu int. Bạn có thể nhận thấy rằng, việc thay đổi giá trị của một mảng sẽ được phản ánh trong một mảng gốc nữa. Có nghĩa là cả hai biến mảng (a và b) đều trỏ đến cùng một đối tượng trong bộ nhớ. Điều này có thể được minh họa bằng sơ đồ dưới đây:

Nếu bạn sao chép một mảng bằng cách sử dụng phương pháp trên, các thay đổi được thực hiện trong một mảng sao chép sẽ được phản ánh trong mảng ban đầu. Thông thường, bạn không muốn những hành vi như vậy trong thực tế. Bạn có thể cần hai đối tượng mảng khác nhau với cùng một bộ các phần tử. Trong các tình huống như vậy, thay vì sử dụng phương pháp trên, chúng ta có thể sử dụng bất kỳ một trong các phương pháp sau đây:

1. Sao chép mảng sử dụng vòng lặp for

package com.maixuanviet.arrays;

public class CopyArrayExample2 {
public static void main(String[] args) {
int[] a = { 12, 21, 0, 5, 7 }; // Declaring and initializing an array of ints

int[] b = new int[a.length]; // Declaring and instantiating another array of ints with same length

// Copy array
for (int i = 0; i < a.length; i++) { b[i] = a[i]; } // Now changing values of one array will not reflect in another array a[2] = 56; // Changing value of 3rd element in array 'a' System.out.println(b[2]); // value of 3rd element in array 'b' will not change = 0 b[4] = 100; // Changing value of 5th element in array 'b' System.out.println(a[4]); // value of 5th element in array 'a' will not change = 7 } } [/code]

2. Sao chép mảng sử dụng phương thức copyOf() của lớp java.util.Arrays

package com.maixuanviet.arrays;

import java.util.Arrays;

public class CopyArrayExample3 {
public static void main(String[] args) {
int[] a = { 12, 21, 0, 5, 7 }; // Declaring and initializing an array of ints

// creating a copy of array ‘a’ using copyOf() method of java.util.Arrays class
int[] b = Arrays.copyOf(a, a.length);

// Printing elements of array ‘b’
for (int i = 0; i < b.length; i++) { System.out.println(b[i]); } // Now changing values of one array will not reflect in other array a[2] = 56; // Changing value of 3rd element in array 'a' System.out.println(b[2]); // value of 3rd element in array 'b' will not change = 0 b[4] = 100; // Changing value of 5th element in array 'b' System.out.println(a[4]); // value of 5th element in array 'a' will not change = 7 } } [/code]

3. Sao chép mảng sử dụng phương thức clone() của lớp java.lang.Object

package com.maixuanviet.arrays;

public class CopyArrayExample4 {
public static void main(String[] args) {
int[] a = { 12, 21, 0, 5, 7 }; // Declaring and initializing an array of ints

// creating a copy of array ‘a’ using clone() method
int[] b = a.clone();

// Printing elements of array ‘b’
for (int i = 0; i < b.length; i++) { System.out.println(b[i]); } // Now changing values of one array will not reflect in other array a[2] = 56; // Changing value of 3rd element in array 'a' System.out.println(b[2]); // value of 3rd element in array 'b' will not change = 0 b[4] = 100; // Changing value of 5th element in array 'b' System.out.println(a[4]); // value of 5th element in array 'a' will not change = 7 } } [/code]

4. Sử dụng phương thức arraycopy() của lớp System

package com.maixuanviet.arrays;

public class CopyArrayExample5 {
public static void main(String[] args) {
int[] a = { 12, 21, 0, 5, 7 }; // Declaring and initializing an array of ints

// Creating an array object of same length as array ‘a’
int[] b = new int[a.length];

// creating a copy of array ‘a’ using arraycopy() method of System class
System.arraycopy(a, 0, b, 0, a.length);

// Printing elements of array ‘b’
for (int i = 0; i < b.length; i++) { System.out.println(b[i]); } // Now changing values of one array will not reflect in other array a[2] = 56; // Changing value of 3rd element in array 'a' System.out.println(b[2]); // value of 3rd element in array 'b' will not change = 0 b[4] = 100; // Changing value of 5th element in array 'b' System.out.println(a[4]); // value of 5th element in array 'a' will not change = 7 } } [/code]

Related posts:

Introduction to Java Serialization
Registration – Password Strength and Rules
Java Program to Find k Numbers Closest to Median of S, Where S is a Set of n Numbers
Java Program to Find the Median of two Sorted Arrays using Binary Search Approach
Disable DNS caching
Using the Not Operator in If Conditions in Java
Java Program to Implement Quick Sort with Given Complexity Constraint
Using Spring @ResponseStatus to Set HTTP Status Code
Refactoring Design Pattern với tính năng mới trong Java 8
Spring 5 Functional Bean Registration
Java Program to Find Second Smallest of n Elements with Given Complexity Constraint
Java Program to Implement Hash Tables with Double Hashing
Zipping Collections in Java
Java Program to Implement Affine Cipher
Netflix Archaius with Various Database Configurations
Java – Write a Reader to File
Java Program to Compute Discrete Fourier Transform Using Naive Approach
Spring Security – security none, filters none, access permitAll
Spring Security and OpenID Connect
Java Program to Implement Expression Tree
Jackson Date
Java Program to Implement Insertion Sort
Tips for dealing with HTTP-related problems
How to Iterate Over a Stream With Indices
The Thread.join() Method in Java
Guide to Character Encoding
Jackson Annotation Examples
Java Program to Implement Heap’s Algorithm for Permutation of N Numbers
Java Program to Implement ScapeGoat Tree
Java Program to Implement Iterative Deepening
Java Program to Implement Pollard Rho Algorithm
Java Program to Generate Date Between Given Range