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:

Anonymous Classes in Java
Jackson vs Gson
@Lookup Annotation in Spring
Java Program to Implement a Binary Search Tree using Linked Lists
Spring Boot - Application Properties
Java Program to Find Second Smallest of n Elements with Given Complexity Constraint
Calling Stored Procedures from Spring Data JPA Repositories
Intro to the Jackson ObjectMapper
REST Web service: Upload và Download file với Jersey 2.x
Custom HTTP Header with the HttpClient
Java Program to Implement Maximum Length Chain of Pairs
Convert String to int or Integer in Java
Java Program to Solve a Matching Problem for a Given Specific Case
Java Program to Generate All Possible Combinations of a Given List of Numbers
LinkedHashSet trong java
Java Program to Find a Good Feedback Vertex Set
Java Program to Implement the linear congruential generator for Pseudo Random Number Generation
Overview of the java.util.concurrent
Custom JUnit 4 Test Runners
Reactive Flow with MongoDB, Kotlin, and Spring WebFlux
Hướng dẫn Java Design Pattern – Abstract Factory
Java Program to Check the Connectivity of Graph Using BFS
Java Program to Remove the Edges in a Given Cyclic Graph such that its Linear Extension can be Found
Disable DNS caching
Java Program to implement Dynamic Array
Tìm hiểu về Web Service
Registration – Activate a New Account by Email
Java – Try with Resources
Hướng dẫn Java Design Pattern – Service Locator
Hướng dẫn Java Design Pattern – Iterator
Base64 encoding và decoding trong Java 8
Java Program to Use Above Below Primitive to Test Whether Two Lines Intersect