zoo
as an ArrayStored zoo
as an array of Animal
s:
Animal[] zoo = new Animal[ZOO_SIZE];
for (int i = 0; i < ZOO_SIZE; i++) {
Animal[i] = new ...;
}
Problem:
ZOO_SIZE
in advance!Animal
s from our zoo
How can we make our zoo dynamic?
zoo
Array in MemoryHow is Animal[] zoo
actually stored in our computer’s memory?
Think Locally!
Zoo
in JavaHigh level picture—a Linked List:
class
esWhat do we need?
class Node
representing enclosure
Animal
Node
class Zoo
Node
(if any)Nodes
(if any)Animal
sAnimal
Animal
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;
}
}
Zoo
Classpublic class Zoo {
private Node head = null;
private Node tail = null;
public void add (Animal a) {...}
public void feedAnimals () {...}
public void remove (Animal a) {...}
public boolean contains (Animal a) {...}
}
add
?add
a Platypus
named DougNode
for Dougtail.next
tail
Doug
is in the ListNode
head
and tail
add
in CodeNode
for doug
:
Node nd = new Node(doug);
tail != null
tail.next
:
tail.setNext(nd);
tail
:
tail = nd;
head
, tail
:
head = nd;
tail = nd;
Think about how to implement other Zoo
operations!
feedAnimals
?remove
?contains
?With the array Animal[] zoo
we could access all of the Animal
s 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?