intro to arrays Flashcards
array
> Collection of values that can be treated as a unit or individually
a very useful data structure provided by Java and other programming languages
sequence of variables of the same type
objects (hence allocated on heap) with a reference on the stack
(visualize an array as a set of variables one after another)
int[] a = new int[5];
data structure
mechanism for storing data in a structured way
what does “sequence of variables of the same type” mean?
> Homogeneous data structure (values of the same type (“base type”) )
Size (quantity) fixed when space is allocated
Ordered
do arrays have default values?
Yes!
“instance variables” of array = cells in array
are assigned default values (0 / null / etc.) when array is created
array variable declaration
int[] a or int a[];
array object creation
new int[5]
or combo: int[] a = new int[1];
(creates an array of 5 cells in the heap)
array indexing
mechanism for accessing individual elements of an array a[0]
to modify arrays:
o modify contents of cell #2 to 6 and cell #1 to 74:
a[2] = 6;
a[1] = 74;
to use arrays
System.out.println(“value = “ + (a[1]-a[2]));
why are cells are just like variables
They may be read: x = a[3];
They may be written: a[2] = 7;
to process all elements in an array
for (int i = 0; i < a.length; i++){
…process the one element at a[i]…
}
what does this do in heap?
int[] a = new int[5];
int[] b = a;
aliasing
what does this do in heap? int[] a = new int[5]; int[] b = new int[a.length]; for (int i = 0; i < a.length; i++){ b[i] = a[i]; }
create a new object copy
is an array’s length mutable or immutable?
a.length is immutable!
explain how to enlarge an array
- Create a new larger array object
- Copy old array contents into new object
- Assign address of new object to variable