Java Reference
In-Depth Information
if(start == null) // Is the list empty?
start = end = newEnd; // Yes, so new element is start and end
else { // No, so append new element
end.next = newEnd; // Set next variable for old end
end = newEnd; // Store new item as end
}
}
// Get the first object in the list
public Object getFirst() {
current = start;
return start == null ? null : start.item;
}
// Get the next object in the list
public Object getNext() {
if(current != null)
current = current.next; // Get the reference to the next item
return current == null ? null : current.item;
}
private ListItem start = null; // First ListItem in the list
private ListItem end = null; // Last ListItem in the list
private ListItem current = null; // The current item for iterating
private class ListItem {
// Class definition as before
}
}
This will create a linked list containing any types of objects. The class has data members to track the
first and last items in the list, plus the member
current
, which will be used to iterate through the list.
We have three class constructors. The default constructor creates an empty list. There is a constructor to
create a list with a single object, and another to create a list from an array of objects. Any list can also
be extended by means of the
addItem()
method. Each of the constructors, apart from the default, sets
the
current
member to the first item in the list, so if the list is not empty this will refer to a valid first
item. You can see that since the
ListItem
class is a member of the
LinkedList
class, we can refer to
its data members directly. This obviates the need for any methods in the
ListItem
class to get or set
its fields. Since it is
private
it will not be accessible outside the
LinkedList
class so there is no risk
associated with this - as long as we code the
LinkedList
class correctly of course.
The
addItem()
method works in much the same way as the
addPoint()
method did in the
PolyLine
class. It creates a new
ListItem
object, and updates the next member of the previous last
item to refer to the new one. The complication is the possibility that the list might be empty. The check
in the
if
takes care of this. We take special steps if
start
holds a
null
reference.
The
getFirst()
and
getNext()
methods are intended to be used together to access all the objects
stored in the list. The
getFirst()
method returns the object stored in the first
ListItem
object in
the list, and sets the
current
data member to refer to the first
ListItem
object. After calling the
getFirst()
method, successive calls to the
getNext()
method will return subsequent objects stored
in the list. The method updates
current
to refer to the next
ListItem
object, each time it is called.
When the end of the list is reached,
getNext()
returns
null
.