ArrayLists


A More Complete Example

The example below constructs an empty list of fish, constructs 10 fish and adds them to the list, and then steps through the list asking each fish to move forward.

    // Construct a list (initially empty) that could hold fish.
    ArrayList<AquaFish> fishList = new ArrayList<AquaFish>();

    // Construct 10 new fish and add them to the list.
    for ( int i = 0; i < 10; i++ )
    {
        AquaFish aNewFish = new AquaFish(aqua);
        fishList.add(aNewFish);
        aqua.add(aNewFish);     // For display purposes
    }

    // Move each fish forward, without changing direction.
    for ( int i = 0; i < fishList.size(); i++ )
    {
        AquaFish aFish = fishList.get(i);
        aFish.moveForward();
        // Or, fishList.get(i).moveForward();
    }

(This is a simplified version of code that might appear in the Aquarium Lab Series.)


Alyce Brady, Kalamazoo College