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 wheel Sieve to Generate Prime Numbers Between Given Range
Java Program to Compute the Area of a Triangle Using Determinants
Java Program to Perform Sorting Using B-Tree
Hướng dẫn Java Design Pattern – Service Locator
Java Program to Implement Max-Flow Min-Cut Theorem
Java – Convert File to InputStream
Introduction to the Java NIO Selector
Java Program to Implement Stack API
How To Serialize and Deserialize Enums with Jackson
Spring Boot - Admin Server
Java Program to Implement Merge Sort Algorithm on Linked List
A Guide to Java SynchronousQueue
Java Program to Implement Merge Sort on n Numbers Without tail-recursion
Java Program to Optimize Wire Length in Electrical Circuit
Java Program to Check Whether it is Weakly Connected or Strongly Connected for a Directed Graph
Class Loaders in Java
Java Program to Perform the Sorting Using Counting Sort
Generating Random Numbers in a Range in Java
Map to String Conversion in Java
Tìm hiểu cơ chế Lazy Evaluation của Stream trong Java 8
Flattening Nested Collections in Java
Java Program to Check Whether an Input Binary Tree is the Sub Tree of the Binary Tree
Java Program to Implement Rope
Java Program to Implement the RSA Algorithm
Java Program to Solve any Linear Equations
An Intro to Spring Cloud Vault
Java Program to Perform Addition Operation Using Bitwise Operators
SOAP Web service: Authentication trong JAX-WS
How to Return 404 with Spring WebFlux
Java Program to Implement Radix Sort
Derived Query Methods in Spring Data JPA Repositories
Assert an Exception is Thrown in JUnit 4 and 5