我能在 Java 中從另一個數組引用一個數組的元素嗎?
可以,你可以 −
int [] myArray1 = {23, 45, 78, 90, 10};
int [] myArray2 = {23, 45, myArray1[2], 90, 10};但是,一旦你這樣做,第二個陣列會儲存該值的引用,而不是整個陣列的引用。因此,陣列中的任何更新都不會影響被引用的值 −
示例
import java.util.Arrays;
public class RefferencingAnotherArray {
public static void main(String args[]) {
int [] myArray1 = {23, 45, 78, 90, 10};
int [] myArray2 = {23, 45, myArray1[2], 90, 10};
System.out.println("Contents of the 2nd array");
System.out.println(Arrays.toString(myArray2));
myArray1[2] = 2000;
System.out.println("Contents of the 2nd array after updating ::");
System.out.println(Arrays.toString(myArray2));
System.out.println("Contents of the 1stnd array after updating ::");
System.out.println(Arrays.toString(myArray1));
}
}輸出
Contents of the 2nd array [23, 45, 78, 90, 10] Contents of the 2nd array after updating :: [23, 45, 78, 90, 10] Contents of the 1stnd array after updating :: [23, 45, 2000, 90, 10]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP