0

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));
     }
  }
Lin S
  • 63
  • 1
  • 7

2 Answers2

1

The locations field is a reference to an array.

This points that reference to a new array of 5 integers.

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

This re-points that reference to a different array.

this.locations= locations;

The new array has its own size. It's not limited by the size of the array that the reference formerly pointed to.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
0

There is a simple mistake you are making, the variable int [] locations = new int[5]; does not actually contain an array of length 5. It is actually just holding the reference to the array of length 5 somewhere on the heap.

This is exactly what this statement below is also doing,

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

so when you are running this.locations= locations;, you are actually saying the variable now refers to the array locationOfShips

If this is not clear i suggest you read about pass by reference good explanation here (Are arrays passed by value or passed by reference in Java?)