gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:44:09 25 4
gpt4 key购买 nike

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?

这将引用重新指向不同的数组。

this.locations= locations;

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

关于java - 数组实例变量与setter方法摄入无关吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56798293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com