Java Reference
In-Depth Information
{
next = nextNode;
}
// end setNextNode
}
// end Node
3.28
The class
LinkedBag
can access
Node
, as just given in Listing 3-5, if both classes are in the same
package and we modify
LinkedBag
slightly. Each occurrence of
Node
within
LinkedBag
must now
appear as
Node<T>
. We begin to make these changes to
LinkedBag
and highlight them in Listing 3-6.
LISTING 3-6
The class
LinkedBag
when
Node
is in the same package
package
BagPackage;
public class
LinkedBag<T>
implements
BagInterface<T>
{
private
Node<T> firstNode;
. . .
public boolean
add(T newEntry)
{
Node<T> newNode =
new
Node<T>(newEntry);
newNode.setNextNode(firstNode);
firstNode = newNode;
numberOfEntries++;
return true
;
}
// end add
. . .
}
// end LinkedBag
Project 3 at the end of this chapter asks you to complete this revision of
LinkedBag
.
3.29
As an inner class with a declared generic type.
The version of
LinkedBag
just described in
Listing 3-6 could define
Node
as an inner class.
Node
would be similar to the class given in
Listing 3-5, but would require the following changes:
•
Omit the
package
statement.
•
Make the class, constructors, and methods private.
•
Replace the generic type
T
with another identifier, such as
S
.
Since both
LinkedBag
and
Node
declare generic types, they must use different identifiers to repre-
sent them.
Project 4 at the end of the chapter asks you to revise
Node
and
LinkedBag
as described here.
3.30
You have seen how to use a chain in the implementation of the ADT bag. One of the greatest
advantages of this approach is that the chain, and therefore the bag, can grow and shrink in size as
necessary. As long as memory is available, you can add as many nodes to a chain as you wish.