可以在 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]

更新於: 2020 年 6 月 16 日

434 次瀏覽

啟動你的職業生涯

透過完成該課程獲得認證

開始吧
廣告
© . All rights reserved.