数组实例变量与setter方法摄入无关吗?

Does the array instance variable not relate to the setter method intake?

In the main method I make a new object of the DotComClass and set locationOfShips array to 14 numbers. Then send those values as an argument over to the setter method (setLocations) in the other class (see below). My question is why does it allow that pass over without issue, since I set the max number of elements of the locations instance variable is 5?


  import java.util.Arrays;

  public class Main {
    public static void main(String[] args) {
      DotComClass dotCom = new DotComClass();
      int[] locationOfShips = {6,7,8,9,1,2,3,4,4,4,4,5,5,5};        
      dotCom.setLocations(locationOfShips);       
    }
  }

  public class DotComClass {
   int [] locations = new int[5]; // is this not related to the locations in the setter?

   public void setLocations (int[] locations){
     this.locations= locations;
     System.out.println(Arrays.toString(locations));
     }
  }

locations 字段是对数组的引用

这指向一个包含 5 个整数的新数组。

int [] locations = new int[5]; // is this not related to the locations in the setter?

这个 re-points 引用了一个 不同的 数组。

this.locations= locations;

新数组有自己的大小。它不受引用以前指向的数组大小的限制。

您犯了一个简单的错误,变量 int [] locations = new int[5]; 实际上并不包含长度为 5 的数组。它实际上只是在堆中某处保存对长度为 5 的数组的引用。

这正是下面这条语句所做的,

int[] locationOfShips = {6,7,8,9,1,2,3,4,4,4,4,5,5,5};

所以当你是 运行 this.locations= locations; 时,你实际上是在说变量现在指的是数组 locationOfShips

如果不清楚,我建议您在此处阅读有关按引用传递的良好解释 (Are arrays passed by value or passed by reference in Java?)