LinkedList class
In this chapter you will learn:
LinkedList class
The LinkedList
class extends AbstractSequentialList
and implements the List
, Deque
, and Queue
interfaces.
It provides a linked-list data structure.
LinkedList is a generic class that has this declaration:
class LinkedList<E>
E
specifies the type of objects that the list will hold.
A demonstration of a linked list of nodes
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
//jav a 2 s . c o m
public class Main {
public static void main(String[] args) {
List<String> ls = new LinkedList<String>();
String[] weekDays = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
for (String weekDay : weekDays){
ls.add(weekDay);
}
dump("ls:", ls);
ls.add(1, "A");
ls.add(3, "B");
ls.add(5, "C");
dump("ls:", ls);
ListIterator<String> li = ls.listIterator(ls.size());
while (li.hasPrevious()){
System.out.print(li.previous() + " ");
}
}
static void dump(String title, List<String> ls) {
System.out.print(title + " ");
for (String s : ls){
System.out.print(s + " ");
}
System.out.println();
}
}
Because LinkedList implements the Deque interface, you have access to the methods defined by Deque.
For example,
- To add elements to the start of a list you can use
addFirst( )
orofferFirst( )
. - To add elements to the end of the list, use
addLast( )
orofferLast( )
. - To obtain the first element, you can use
getFirst( )
orpeekFirst( )
. - To obtain the last element, use
getLast( )
orpeekLast( )
. - To remove the first element, use
removeFirst( )
orpollFirst( )
. - To remove the last element, use
removeLast( )
orpollLast( )
.
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Collections