14.6. Linked Lists

The LinkedList<> generic collection type implements a generalized linked list. You have already seen quite a few of the methods that the class implements, as the members of the List<> interface are implemented in the Vector<> class. Nonetheless, let's 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 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 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 type corresponding to the type argument you supplied when you created the LinkedList<> object, and neither returns 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 ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.