Java Reference
In-Depth Information
SOLUTION 5.4
The program prints out the number
4
.
Only three machines are in the
plant
factory, but machine
m
is counted by both
plant
and
bay
. Both of these objects contain lists of machine components that refer to machine
m
.
The results could be worse. If, say, an engineer adds the
plant
object as a component of the
bay
composite, a call to
getMachineCount()
will enter an infinite loop.
SOLUTION 5.5
A reasonable implementation of
MachineComposite.isTree()
is:
protected boolean isTree(Set visited)
{
visited.add(this);
Iterator i = components.iterator();
while (i.hasNext())
{
MachineComponent c = (MachineComponent) i.next();
if (visited.contains(c) || !c.isTree(visited))
{
return false;
}
}
return true;
}