LinkList maintains a linked-list of simple graphics commands, and displays the shapes during the paint method.
Use the [Add] button to add a new command at the end of the list. Use [Undo] to remove the last command from the end of the list. The [List] button displays all the commands.
Java has no extra construct for creating "record" types. Instead, a group of "fields" can be encapsulated in an inner-class (Node).
Java has no pointers like C++. Java has references (similar to pointers), but you cannot manipulate them directly - e.g. you cannot do arithmetic on the reference values. The references can only be used to retrieve values.
So a linked-list is formed by creating a class called Node, instantiating lots of Node objects via the new command, and linking these together using the next reference variable.
Linked-lists seem complicated to program, and might not seem more useful than an array (which is easier to program). But it is possible for a linked-list Node to contain any quantity or any type of data, whereas arrays are type-specific and occupy a fixed size. Thus linked-lists provide more flexibility than arrays.
class Node
A Node is declared in an inner-class - that is a non-public
class defined inside the current class. It is very simple, containing
only 2 variables (properties) : command and next.
Node next = null;
The next variable is a reference (pointer) connecting one Node
to the next Node.
Node head = null;
Node tail = null;
head and tail will point to the first and last nodes in the
linked-list. At the beginning, the point nowhere, as no Nodes exist
yet.
tail.next = new Node();
Create a new Node, and attach it to the end of the linked-list.
head.command = "s 100 150 100";
Copies a String into the command field in the first node in the list.
Node temp = head;
Make a new temporary pointer, and assign it to point at the first node in
the linked-list.
temp = temp.next;
Move temp to point at the next node in the linked-list.
while (temp != null)
Loop until temp goes past the end of the linked-list.
This program is not fully error-trapped. A NullPointerException will occur if temp.command is accessed when temp is pointing at null.
The deleteTail method avoids NullPointerExceptions by never deleting if there is only one Node in the linked-list.
A "real" program needs to allow inserting and deleting at any position in the list.
Linked-lists exist in RAM, and disappear when the program stops running. It would be useful to save the Linked-List in a file.
Although this might not seem more useful than an array, it is possible for a linked-list Node to contain any quantity or type of data, whereas arrays are type-specific and occupy a fixed size.