Java Reference
In-Depth Information
algorithms you'll need to convert each high-level language statement into machine-lan-
guage instructions. If you enjoy being challenged, you might attempt the enhancements
to both the compiler and the Simpletron Simulator suggested in the exercises.
21.2 Self-Referential Classes
A self-referential class contains an instance variable that refers to another object of the
same class type. For example, the generic Node class declaration
class Node<T>
{
private T data;
private Node<T> nextNode; // reference to next linked node
public Node(T data) { /* constructor body */ }
public void setData(T data) { /* method body */ }
public T getData() { /* method body */ }
public void setNext(Node<T> next) { /* method body */ }
public Node<T> getNext() { /* method body */ }
}
has two private instance variables— data (of the generic type T ) and Node<T> variable
nextNode . Variable nextNode references a Node<T> object, an object of the same class being
declared here—hence the term “self-referential class.” Field nextNode is a link —it “links”
an object of type Node<T> to another object of the same type. Type Node<T> also has five
methods: a constructor that receives a value to initialize data , a setData method to set the
value of data , a getData method to return the value of data , a setNext method to set the
value of nextNode and a getNext method to return a reference to the next node.
Programs can link self-referential objects together to form such useful data structures
as lists, queues, stacks and trees. Figure 21.1 illustrates two self-referential objects linked
together to form a list. A backslash—representing a null reference—is placed in the link
member of the second self-referential object to indicate that the link does not refer to
another object. The backslash is illustrative; it does not correspond to the backslash char-
acter in Java. By convention, in code we use the null reference to indicate the end of a
data structure.
15
10
Fig. 21.1 | Self-referential-class objects linked together.
21.3 Dynamic Memory Allocation
Creating and maintaining dynamic data structures requires dynamic memory alloca-
tion —allowing a program to obtain more memory space at execution time to hold new
nodes and to release space no longer needed. Remember that Java does not require you to
explicitly release dynamically allocated memory. Rather, Java performs automatic garbage
collection of objects that are no longer referenced in a program.
The limit for dynamic memory allocation can be as large as the amount of available
physical memory in the computer or the amount of available disk space in a virtual-
 
 
 
Search WWH ::




Custom Search