Chapter 6: Arrays and Array Lists
Chapter 6: Arrays and Array Lists
Initialization
An array is an object, so the keyword new must be used when creating an array. The size
of an array cannot be changed, and is immutable, but just like a String, an array reference
may be reassigned to a new array of a different size.
//Initializer Lists
//Initializer lists are examples in which the keyword new is not required to create a new array.
int[] coins = new int[4]; // This is too much work. Look below...
coins[0] = 1;
coins[1] = 5;
coins[2] = 10;
coins[3] = 25;
int[] coins = {1, 5, 10, 25} // Only works if you know len before, no new keyword.
Length of Array
For arrays, in order to loop through one, what you need is the length of an array. In order
to find the length of an array, it is actually not that difficult. Simply, if you have an array
However, remember that length is not a method, and thus, unlike the String length, it
does not need parentheses after. Do not put parentheses after.
Traversing an Array
When traversing an array, make sure that you recognize that:
When using a for each loop, you may not replace or remove any elements in the array,
although you may access each of the elements.
When using a for loop, you may replace or remove any elements in the array, access
the index of any element, or access each of the elements.
Arrays as Parameters
Since arrays are treated as objects, passing an array as a parameter means passing its
object reference. There is no copy made of the array.
This means that the elements of the actual array can be accessed and modified.
This means that primitive types, including single array elements of type int or double, are
passed by value. Here, a copy is made of the actual parameter, and the copy is erased on
exiting the method.
This means that in the case where for a certain method, the parameter is "int[] b", in that
case, the elements in array b are passed by reference, making them mutable. However, if
the parameter is "int b" and the parameter inputted is, for example, b[0], an int is being
passed into that function, and thus, that is passed by value.
Always pass by reference when wanting to change, or mutate, certain values in the
array. It is necessary.