๐Ÿ—’๏ธ Ben's Notes

Arrays

Content Note

This page assumes prior knowledge of Python lists from CS61A or equivalent.

Arrays are a very popular data structure that stores an indexed list of data.

An artistic interpretation of a new int[5] {6, 1, 2, 3, 99};

Properties #

  • Fixed length: after instantiation, the length of an array cannot be changed.
  • Every value in array is the same type and holds the same amount of bits in memory.
  • Zero-indexed. That means arr[0] returns the first value, and arr[arr.length] is out of bounds.
  • No methods. Helper methods from other libraries (like System.arraycopy) need to be used to manipulate arrays.
  • Retrieval is independent of size and takes constant time regardless of how big arrays are.

Using Arrays in Java #

Instantiation:

  • int[] a = {1, 2, 3, 4, 5}; assigns values.
  • int b = new int[3]; creates array of provided length populated with default values.

Copying

Multidimensional Arrays

  • int[][] 2d = new int[4][4];or int[][] 2d = new int[][] {{1}, {2, 3}, {4, 5, 6}};will create arrays inside of an array. This is useful for storing matrices, coordinate maps, or any other multidimensional data!

Generic Arrays

  • Arrays of generic objects are NOT allowed! Use ArrayLists instead.
  • Or, this workaround can be used:Type[] items = (Type[]) new Object[length]

Array Lists #

Java has another built-in type that uses an array under the hood, which is the ArrayList. Hereโ€™s how ArrayLists are different from normal arrays: