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:

Jackson – Marshall String to JsonNode
Java Program to Check for balanced parenthesis by using Stacks
Một số ký tự đặc biệt trong Java
Use Liquibase to Safely Evolve Your Database Schema
Introduction to Spliterator in Java
Guide to System.gc()
Java Program to Give an Implementation of the Traditional Chinese Postman Problem
Xây dựng ứng dụng Client-Server với Socket trong Java
Java Program to Implement Queue using Linked List
Java Program to Implement RoleList API
Java Program to Implement Coppersmith Freivald’s Algorithm
DynamoDB in a Spring Boot Application Using Spring Data
Hướng dẫn sử dụng biểu thức chính quy (Regular Expression) trong Java
Java Program to Implement ConcurrentHashMap API
Simple Single Sign-On with Spring Security OAuth2
A Custom Data Binder in Spring MVC
Tìm hiểu cơ chế Lazy Evaluation của Stream trong Java 8
Java Program to implement Dynamic Array
Entity To DTO Conversion for a Spring REST API
Guide to the Volatile Keyword in Java
Java Program to Implement Ternary Tree
Java Program to Implement HashTable API
Spring Boot with Multiple SQL Import Files
Java Program to Find the Shortest Path from Source Vertex to All Other Vertices in Linear Time
Spring Cloud AWS – Messaging Support
Toán tử instanceof trong java
Guide to CopyOnWriteArrayList
Changing Annotation Parameters At Runtime
Java Program to Implement Quick Hull Algorithm to Find Convex Hull
Java Program to Implement First Fit Decreasing for 1-D Objects and M Bins
The Spring @Controller and @RestController Annotations
Java Program to Implement Hash Tables with Double Hashing