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;
Новый массив имеет собственный размер. Он не ограничен размером массива, на который раньше указывала ссылка.
Вы совершаете простую ошибку: переменная 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
Если это неясно, я предлагаю вам прочитать хорошее объяснение передачи по ссылке здесь (Передаются ли массивы по значению или по ссылке в Java?)
Спасибо, это имело смысл.
Спасибо это помогло