Overview

1. A zoo as an Array

Previously

Stored zoo as an array of Animals:

Animal[] zoo = new Animal[ZOO_SIZE];

for (int i = 0; i < ZOO_SIZE; i++) {
Animal[i] = new ...;
}


Problem:

• We need to specify ZOO_SIZE in advance!
• But we may want to add/remove Animals from our zoo

How can we make our zoo dynamic?

A zoo Array in Memory

How is Animal[] zoo actually stored in our computer’s memory?

Another Way to Store a Zoo

Think Locally!

• Consider an actual zoo
• Each animal is in some kind of enclosure
• Each enclosure has:
• another sign pointing to next enclosure
• This is enough information to navigate the zoo and see all animals

Thinking classes

What do we need?

1. class Node representing enclosure
• stores (reference to) an Animal
• stores (reference to) next Node
2. class Zoo
• stores (reference to) first Node (if any)
• stores (reference to) last Nodes (if any)
• implements desired operations:
• feed Animals
• add an Animal
• remove an Animal

Implementing Node

class Node {
private Animal animal;
private Node next;

public Node (Animal animal) {
this.animal = animal;
next = null;
}

public void setNext (Node nd) {
next = nd;
}

public Node getNext () {
return Next;
}

public Animal getAnimal () {
return animal;
}
}


Making the Zoo Class

public class Zoo {
private Node tail = null;

public void add (Animal a) {...}

public void feedAnimals () {...}

public void remove (Animal a) {...}

public boolean contains (Animal a) {...}
}


add in Code

1. Create a Node for doug:
 Node nd = new Node(doug);

2. If tail != null
• Update tail.next:
  tail.setNext(nd);

• Update tail:
  tail = nd;

3. Else
• Set head, tail:
  head = nd;
tail = nd;


Activity

Think about how to implement other Zoo operations!

• Feed all the animals
• Remove an animal
• Determine if the zoo contains a given animal

Another Question

With the array Animal[] zoo we could access all of the Animals easily:

Animal[] zoo;
...
for (int i = 0; i < zoo.length; i++) {
// do something with zoo[i]
}


How could we do something similar with the Zoo class?

• Generics
• Interfaces
• Iterators