ArrayLists and Arrays


  1. This example class NestedSquare2 is a client of the ArrayList class.
    import java.util.ArrayList;
    ...
    
    public class NestedSquare2 
    {
       private static final double SHIFT = 2;
       private ArrayList squares;
       ...
            squares = new ArrayList();
    
            for (int i = (int) size; i >= 4; i -= 2*SHIFT)
            {
               squares.add(new FramedRect( x, y, size, size, canvas ));
               x = x + SHIFT;
               y = y + SHIFT;
               size = size - 2 * SHIFT;
            }
       ...   
    }
    
    Notice that the PIV (Private Instance Variable) squares is an ArrayList object. Using this way to access and remember each of the nested squares means that RECURSION is not necessary. Compare to the former NestedSquares class, which was a recursively defined class.

    Using an ArrayList class (See chapter 13 of Big Java textbook - pages 521-530).

    Also see the online Java documentation and look at the get(), size(), add() and remove() and clear() ArrayList methods.

  2. Implementing NestedSquare2 with an array instead of using an ArrayList object. (Not ready yet).