/** * ArrayListDriver.java * * Demonstrates a few of the methods for working with an ArrayList. * * @author Tom Cormen */ import java.util.ArrayList; import java.util.Random; public class ArrayListDriver { private static final int MAX_X = 200, MAX_Y = 150; // max coordinate values private static final double MAX_RADIUS = 100.0; // size of largest circle public static void main(String[] args) { ArrayList shapes = new ArrayList(); // a polymorphic ArrayList Random generator = new Random(); // random number generator final int INIT_LIST_SIZE = 8; // Randomly add some shapes to the ArrayList. for (int i = 0; i < INIT_LIST_SIZE; i++) { shapes.add(getRandomShape(generator)); } // See what we've got. System.out.println("After adding " + INIT_LIST_SIZE + " shapes:"); for (int i = 0; i < shapes.size(); i++) System.out.println(shapes.get(i)); // Insert a shape into the middle of the ArrayList. GeomShape latecomer = getRandomShape(generator); shapes.add(3, latecomer); // See what we've got now. System.out.println("\nAfter adding:"); for (int i = 0; i < shapes.size(); i++) System.out.println(shapes.get(i)); // And delete a shape from the middle of the ArrayList. shapes.remove(5); // See what we've got now. System.out.println("\nAfter removing:"); for (int i = 0; i < shapes.size(); i++) System.out.println(shapes.get(i)); // Find where we put the latecomer. System.out.println("\nThe latecomer is at index " + shapes.indexOf(latecomer)); } /** * Create a randomly generated shape object. * * @param generator * @return an object that implements the GeomShape interface */ public static GeomShape getRandomShape(Random generator) { // Randomly pick a Circle or Rectangle to create. if (generator.nextInt(2) == 0) // Chose Circle. Randomly choose a center and radius. return new Circle(generator.nextInt(MAX_X), generator.nextInt(MAX_Y), generator.nextDouble() * MAX_RADIUS); else { // Chose Rectangle. Randomly choose its corners. int x1 = generator.nextInt(MAX_X); int x2 = generator.nextInt(MAX_X); int y1 = generator.nextInt(MAX_Y); int y2 = generator.nextInt(MAX_Y); return new Rectangle(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x1 - x2), Math.abs(y1 - y2)); } } }