Java Reference
In-Depth Information
Linked Lists
The
LinkedList
collection class implements a generalized linked list. We have already seen quite a
few of the methods that the class implements as the members of the
List
interface implemented in the
Vector
class. Nonetheless, let's quickly go through 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 will create a
LinkedList
object containing 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 we 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 type
Object
and do not 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 in the list by using the
getFirst()
and
getLast()
methods, respectively. To remove an object you can 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
removeLast()
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 value and the second argument is the new object at that position. The old
object is returned and the method will throw 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()
. You will recall that an
Iterator
object
only allows you to go forward through the elements, whereas a
ListIterator
enables you to iterate
backwards or forwards.
We could change the
TryPolyLine
example from Chapter 6 to use a
LinkedList
collection object
rather than our homemade version.
Try It Out - Using a Genuine Linked List
We will put this example in a new directory,
TryNewPolyLine
. We can use the
TryPolyLine
class
that contains
main()
and the
Point
class exactly as they are, so if you still have them, copy the source
files to the new directory. We just need to change the
PolyLine
class definition:
import java.util.*;
public class PolyLine {
// Construct a polyline from an array of points
public PolyLine(Point[] points) {
// Add the points
for(int i = 0; i < points.length; i++)
polyline.add(points[i]);
}