Multi-dimensional arraysTopFinishing Arrays

Finishing Arrays

Hopefully the example code helped you understand the differences between lists in Grace and arrays in Java. But let's now take a look at how we write some of the methods for lists in Grace that are not available in Java for arrays.

Let's look first at adding a new element to an array. For simplicity, let's assume that we are working with an array seq of type SomeThing and instance variable size keeps track of the number of elements in seq that are in use. We assume that size <= seq.length.

Adding a new element to the end of seq is pretty straightforward:

public void addLast(SomeThing newElt) {
   if (size < seq. length) {
      seq[size] = newElt;
      size++;
   }

However, adding an element to the beginning of a list is much trickier. To add the new element we need to make a space by shifting all of the other elements over by 1.

public void addFirst(SomeThing newElt) {
   if (size < seq. length) {
      // shift over existing elements
      for (int index = size-1; index >= 0; index--) {
         seq[index+1] = seq[index]
      }
      seq[0] = newElt;
      size++;
   }

Exercise Why do we shift the last element to the right first, rather than shifting the element at 0 first?

Exercise Explain in detail what would happen if you made the horrible mistake of replacing the +1 in the assignment statement in the forloop by.

         seq[index++] = seq[index]

Explain why these horrible things happened and write on the board 100 times "I will never use ++ in the middle of an expression!".


Multi-dimensional arraysTopFinishing Arrays