Why can I pass a large array to a smaller array in Java?

It might be a dumb question, but does a Java array take more than its size? If so, why do we need an ArrayList? I thought that arrays have a fixed size that cannot be increased at runtime. Here is my test code:

public class ArraySizeDemo {
    int[] anArray = new int[5];

    public int[] getAnArray() {
        return anArray;
    }

    public void setAnArray(int[] anArray) {
        this.anArray = anArray;
    }
}

public class ArrayDemo {
    public static void main(String[] args) {
        ArraySizeDemo ar = new ArraySizeDemo();

        int arr[] = {0,1,2,3,4,5,6,7,8,9};
        int testarray[] = new int[10];
        ar.setAnArray(arr); // it should give an error here since I am trying to 
        // assign an array of 10 to an array of 5
        testarray = ar.getAnArray();
        for (int i = 0; i < arr.length; i++)
            System.out.println(testarray[i]);
    }
}
+6
source share
4 answers

Appointment

this.anArray = anArray;

Don't copy items anArrayto this.anArray.

It changes the value of the variable this.anArrayto refer to the same array that it refers to anArray. Therefore, before assignment, an this.anArrayarray of length 5 is referenced, and after assignment, it refers to another array object of length 10.

() , , , 10 5.

+17

this.anArray this.anArray = anArray;.

this.anArray , , .

+6

5. .

, :

public void setAnArray(int[] anArray) {
    for (int i = 0; i < anArray.length; i++) {
        this.anArray[i] = anArray[i];
    }
}

, , 5 10:

public void setAnArray(int[] anArray) {
    this.anArray = anArray;
}
+6

ArraySizeDemo = > ArraySizeDemo ar = new ArraySizeDemo();, , -

Memory : 
-------------------------
...
anArray point to 0x100        
...  
-------------------------

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

Memory : 
-------------------------
...
anArray point to 0x111
arr     point to 0x222    
...  
-------------------------

and when ar.setAnArray(arr)you call, you transfer the link arr, which is in the demo version0x222

and in the body setAnArray()you change the link anArrayto the transmitted linkthis.anArray = anArray;

so after calling ar.setAnArray(arr)

Memory : 
-------------------------
...
anArray point to 0x222
arr     point to 0x222    
...  
-------------------------
0
source

All Articles