TopScribbles with arraysNew with Java 5

New with Java 5

Java 5 also supports a new shorter way of going through all elements of an array with a for loop. We can write:

    Line[] scribbleLine = new Line[MaxVals];
    ...
    for (int i = 0; i<MaxVals; i++)]
       scribbleLine[i].move(xOffset,yOffset);
    }

or equivalently

    for (Line line:scribbleLine) {
       line.move(xOffset,yOffset);
    }

Note that his only works if the array is full, otherwise you will get a NullPointerException when you send the move message to unfilled slots. This new for construct "iterates" through all of the elements in the array from 0 to MaxVals-1.

Java 5 now includes the class ArrayList that holds an "expandable array". That is, it behaves like an array (though with object syntax), but keeps growing as necessary. See Demo: Drawing program and link

Notice that in each case we do not need to keep track of the number of elements in the ArrayList as the data structure keeps track of it itself. Notice also in the first program that we can just send the delete message to an array list with the index and it will automatically shift everything over to fill the gap. While we only add at the end of the array here, it will also allow us to add something in th middle and shove all of the old elements over to make space.


TopScribbles with arraysNew with Java 5