TopFor loopsArrays

Arrays

Java has a class ArrayLIst<T> that is similar to Grace's lists. However, it also has a more primitive data structure, arrays, that form the building blocks of ArrayList. Here we are going to focus on arrays as it will provide you good intuition on the complexity of list operations. You can look up information about ArrayList is the documentation on Java libraries.

Arrays differ from Grace's list in several important ways. The most important is that arrays have a fixed size that is determined when the array is created. Another is that the operations on an array are limited. You can ask for an element at a given location, update an element at a location, or ask the array for the number of slots it has. However, more complex operations must be hand-coded by the programmer. Finally, the elements of an array are indexed starting at 0 rather than 1 like Grace.

Array types and expressions in Java use a special syntax. If T is a type then T[] is the type of arrays holding elements of type T. Similarly, a new array of T of size n is constructed by writing new T[n]. Thus we can declare and initialize an array a of double with 20 slots by writing:

    double[] a = new double[20]

We access the elements of an array using a similar notation to refer to individual elements. Thus we can obtain the values of the first three elements of the array a by writing a[0], a[1], and a[2]. (Remember that we start numbering the array elements at 0, not 1.)

We can update the elements using a similar notation:

    a[0] = 7.47

(We note here that Grace also allows programmers to access and update list elements using a similar notation. Where we wrote b.at(5), we could obtain the same value using b[5]. Where we updated a value by writing b.at(3)put(3.12), we could also have written b[3] := 3.12. However, we preferred the more traditional method request style because it made it clear that these accesses were all via method requests.)

Because you must allocate all the space for an array when you create it, very often the number of active elements in an array is smaller than the total number of slots. If a is an array, then a.length will return the total number of slots in the array. Thus if a.length returns 20, then the array has elements a[0] through a[19] (because we start counting at 0, the last slot is always at one less than the length). By the way, notice that there are no open and closed parentheses after the method request of length. That is because length is a public instance variable of the array class. We think that is terrible style (if you want an instance variable to be public then you should write a method that returns its value - in Grace when you declare a variable to be readable, the system automatically generates such a method for you - and if you declare it to be public the system generates both "getter" and "setter" methods.


TopFor loopsArrays