Example of a LinkedList August 23, 2006
Posted by deltawing in Computer Science, Java.trackback
Here is a very simple example of a LinkedList to get started with:
import java.util.Iterator;
import java.util.List;
import java.util.LinkedList;
public class LinkedListTest
{
public static void main(String[] args)
{
//create a new LinkedList
List list = new LinkedList();
//adding elements to the list. We are adding Strings.
list.add(“i”);
list.add(“like”);
list.add(“to”);
list.add(“code with”);
list.add(“Java 5”);
//the list object calls the iterator() method of the LinkedList to obtain the iterator
Iterator iter = list.iterator();
while(iter.hasNext())
{
System.out.println(iter.next());
}
}
}
—————————————————————————————–
LinkedLists are:
- Very efficient for inserting and removing elements.
- Not so fast when accessing elements in order (though not slower than a normal ArrayList)
- Slow when randomly accessing elements
- Java 1.5 version supports Autboxing
- Uses an Iterator object to traverse through the elements
- Comes in more flavours – Doubley Linked Lists and Circular Linked Lists.
Please, corrections if mistakes have been made!
why is List list = new LinkedList();
not LinkedList list = new LinkedList(); ?
Because, List is the superclass of linkedlist, that is legal.