在 Java 中设置一个数组等于另一个数组
作者:迹忆客
最近更新:2023/09/14
浏览次数:
在 Java 中有几种方法可以使数组与另一个数组相等。本教程演示如何在 Java 中将一个数组值设置为等于另一个数组值。
在 Java 中设置一个数组等于另一个数组
如上所述,可以使用多种方式将 Java 中的数组设置为与另一个数组相等。这里有几种方法:
让我们尝试一个可以实现上述所有方法的示例。
package jiyik;
import java.util.Arrays;
public class Array_Copy {
public static void main(String args[]) {
//Method 1: Copy array by the same length
String[] Array1 = {"delftstack1", "delftstack2", "delftstack3"};
String[] Array2 = new String[Array1.length];
for (int i = 0; i < Array2.length; i++) {
Array2[i] = Array1[i];
}
System.out.println("Method 1: ");
System.out.print("Array 1: "+Arrays.toString(Array1));
System.out.print("\nArray 2: "+Arrays.toString(Array2));
//Method 2: Using System.arraycopy method
String[] Array3 = {"jiyik1", "jiyik2", "jiyik3"}; String[] Array4 = new String[Array3.length];
System.arraycopy(Array3, 0, Array4, 0, Array4.length);
System.out.println("\nMethod 2: ");
System.out.print("Array 3: "+Arrays.toString(Array3));
System.out.print("\nArray 4: "+Arrays.toString(Array4));
//Method 3: using clone() method
String[] Array5 = {"jiyik1", "jiyik2", "jiyik3"};
String[] Array6 = Array5.clone();
System.out.println("\nMethod 3: ");
System.out.print("Array 5: "+Arrays.toString(Array5));
System.out.print("\nArray 6: "+Arrays.toString(Array6));
//Method 4: using Arrays.copyOf() and Arrays.copyOfRange() methods
String[] Array7 = {"jiyik1", "jiyik2", "jiyik3"};
String[] Array8 = Arrays.copyOf(Array7, 3);
String[] Array9 = Arrays.copyOfRange(Array7, 0, 3);
System.out.println("\nMethod 4: ");
System.out.print("Array 7: "+Arrays.toString(Array7));
System.out.print("\nArray 8: "+Arrays.toString(Array8));
System.out.print("\nArray 9: "+Arrays.toString(Array9));
//Method 5: using clone() method
String[] Array10 = {"jiyik1", "jiyik2", "jiyik3"};
String[] Array11 = Array10;
//Check the side effect
Array10[2]= "Changed";
System.out.println("\nMethod 5: ");
System.out.print("Array 10: "+Arrays.toString(Array10));
System.out.print("\nArray 11: "+Arrays.toString(Array11));
}
}
上面的代码使用了上面描述的所有方法,并在 Java 中设置一个数组等于另一个数组,复制一个数组。见输出:
Method 1:
Array 1: [jiyik1, jiyik2, jiyik3]
Array 2: [jiyik1, jiyik2, jiyik3]
Method 2:
Array 3: [jiyik1, jiyik2, jiyik3]
Array 4: [jiyik1, jiyik2, jiyik3]
Method 3:
Array 5: [jiyik1, jiyik2, jiyik3]
Array 6: [jiyik1, jiyik2, jiyik3]
Method 4:
Array 7: [jiyik1, jiyik2, jiyik3]
Array 8: [jiyik1, jiyik2, jiyik3]Array 9: [jiyik1, jiyik2, jiyik3]
Method 5:
Array 10: [jiyik1, jiyik2, Changed]
Array 11: [jiyik1, jiyik2, Changed]