Home Arrays
Post
Cancel

Arrays

Arrays

  • Like classes, arrays are also sequences of memory boxes. However
    • Classes have named memory boxes (mapped variable names to memory).
    • Class boxes can store different types.
    • Arrays have numbered memory boxes (accessible by index). Arrays do not have methods
    • Array boxes must store the same variable type.
  • Any array has a fixed length

Array Creation

  • There are three ways to create an array:
1
2
3
x = new int[3];
int[] y = new int[]{1, 2, 3, 4, 5};
int[] z = {9, 10, 11, 12, 13}
  • First notation creates an array of length 3 and each memory box is filled with default value 0.
  • Second notation creates an array with the size needed to store the specified values.
  • Third notation declares and creates z, but omits the use of new.

Array Access and Modification

  • We can access array elements using index notation like in python.
    • However, Java does not support negative indexing.
  • Java also has as a method System.arraycopy that copies one section of one array over to a same-length section in another array. Five parameters ar etaken
    • The source array
    • Starting index in the source array
    • The destination array
    • Starting index in the destination array
    • How many items to copy.
1
2
3
4
int[] x = {1,2,3,4,5};
int[] y = new int[5];
System.arraycopy(x, 2, y, 3, 2);
Arrays.toString(y);
1
[0, 0, 0, 3, 4]
  • We may also use a loop to copy over array elements. However, if we run out of index out of bounds errors, Java only catches them at runtime, and not compilation.

2D Java Arrays

  • 2D arrays in Java are just arrays of arrays.
  • However, each element in the parent array doesn’t store the memory boxes of the array, rather, it stores an array reference to the memory location of the child arrays.
This post is licensed under CC BY 4.0 by the author.

CS61B: Lecture 4

CS61B: Lecture 5