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:

Java Program to Implement Gauss Jordan Elimination
Rest Web service: Filter và Interceptor với Jersey 2.x (P1)
Java Program to Implement Multi-Threaded Version of Binary Search Tree
Java Program to implement Sparse Vector
Java Program to Implement Booth Algorithm
Setting Up Swagger 2 with a Spring REST API
Java Program to Create a Random Graph Using Random Edge Generation
Deploy a Spring Boot WAR into a Tomcat Server
Tạo ứng dụng Java RESTful Client không sử dụng 3rd party libraries
An Example of Load Balancing with Zuul and Eureka
Java Program to Implement ScapeGoat Tree
Java Program to Implement Ternary Search Algorithm
Using JWT with Spring Security OAuth (legacy stack)
Java Program to Construct K-D Tree for 2 Dimensional Data
Finding the Differences Between Two Lists in Java
Java Program to Find Nearest Neighbor for Static Data Set
Spring MVC + Thymeleaf 3.0: New Features
Giới thiệu JDBC Connection Pool
Spring 5 WebClient
A Guide to the Java LinkedList
Java Program to Implement ConcurrentSkipListMap API
Configure a RestTemplate with RestTemplateBuilder
The DAO with Spring and Hibernate
Tính trừu tượng (Abstraction) trong Java
Jackson – Bidirectional Relationships
Java Program to Check if a Point d lies Inside or Outside a Circle Defined by Points a, b, c in a Pl...
Java Program to Implement Segment Tree
An Intro to Spring Cloud Contract
Sort a HashMap in Java
Java Program to find the maximum subarray sum O(n^2) time(naive method)
Spring Boot - Zuul Proxy Server and Routing
XML-Based Injection in Spring