Java Reference
In-Depth Information
course, because the Stack<> class is derived from Vector<> , all the Vector<> class methods are avail-
able for a stack when you need them.
I think you'll agree that using a stack is very simple. A stack is a powerful tool in many different contexts.
A stack is often applied in applications that involve syntactical analysis, such as compilers and interpret-
ers — including those for Java.
LINKED LISTS
The LinkedList<T> type implements the List<> interface and defines a generalized linked list. You have
already seen quite a few of the methods that the class implements, as the members of the List<> in-
terface are implemented in the Vector<> class. Nonetheless, here I quickly review the methods that the
LinkedList<> class implements. There are two constructors: a default constructor that creates an empty list
and a constructor that accepts a Collection<> argument that creates a LinkedList<> object that contains
the objects from the collection that is passed to it.
To add objects to a list you have the add() and addAll() methods, exactly as I discussed for a Vector<>
object. You can also add an object at the beginning of a list using the addFirst() method, and you can add
one at the end using addLast() . Both methods accept an argument of a type corresponding to the type ar-
gument you supplied when you created the LinkedList<> object, and neither return a value. Of course, the
addLast() method provides the same function as the add() method.
To retrieve an object at a particular index position in the list, you can use the get() method, as in the
Vector<> class. You can also obtain references to the first and last objects by using the getFirst() and
getLast() methods, respectively. To remove an object you use the remove() method with an argument
that is either an index value or a reference to the object that is to be removed. The removeFirst() and re-
moveLast() methods do what you would expect.
Replacing an existing element in the list at a given index position is achieved by using the set() method.
The first argument is the index and the second argument is the new object at that position. The old object is
returned, and the method throws an IndexOutOfBoundsException if the index value is not within the limits
of the list. The size() method returns the number of elements in the list.
As with a Vector<> object, you can obtain an Iterator<> object by calling iterator() , and you can
obtain a ListIterator<> object by calling listIterator() . Recall that an Iterator<> object enables you
only to go forward through the elements, whereas a ListIterator<> object enables you to iterate backward
and forward.
You could change the TryPolyLine example from Chapter 6 to use a LinkedList<> collection object
rather than your homemade version.
TRY IT OUT: Using a Genuine Linked List
Search WWH ::




Custom Search