This might be a silly question but does a Java array accept more than its size? If yes then why do we need ArrayList? I thought that arrays had a fixed size that can't 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]);
}
}
If you try to access the array position (index) greater than its size, the program gets compiled successfully but, at the time of execution it generates an ArrayIndexOutOfBoundsException exception.
To pass an array as an argument to a method, you just have to pass the name of the array without square brackets. The method prototype should match to accept the argument of the array type. Given below is the method prototype: void method_name (int [] array);
If you create an array by initializing its values directly, the size will be the number of elements in it. Thus the size of the array is determined at the time of its creation or, initialization once it is done you cannot change the size of the array.
Once an array has been created, its size cannot be changed. Instead, an array can only be "resized" by creating a new array with the appropriate size and copying the elements from the existing array to the new one.
The assignment
this.anArray = anArray;
doesn't copy the elements of anArray
to this.anArray
.
It changes the value of the this.anArray
variable to refer to the same array referenced by anArray
. Therefore, before the assignment this.anArray
refers to an array of length 5, and after the assignment it refers to a different array object of length 10.
If instead of this assignment you attempted to copy elements of the source array to the (smaller) target array, an exception would have been thrown, since the length of an array cannot be changed, so the elements of an array of length 10 cannot fit in an array of length 5.
You are changing the reference of this.anArray
doing this.anArray = anArray;
.
After that assignment, this.anArray
is a reference pointing to another array, the one of ten elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With