我能在 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]

更新時間: 16-6 月-2020

433 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告