A Java LinkedList example

I find that I learn a lot — especially initially — when I can see source code examples. To that end, here’s some sample code showing how to use a Java LinkedList. This uses Java syntax prior to Java 5:

package com.devdaily.javasamples;

import java.util.Iterator;
import java.util.LinkedList;

public class JavaLinkedListTest
{

  public JavaLinkedListTest()
  {
    // LinkedList constructor
    LinkedList list = new LinkedList();
    list.add("Hello");
    list.add("world");
    // keep adding here ...

    // iterate over the LinkedList    
    Iterator it = list.iterator();
    while (it.hasNext())
    {
      String s = (String)it.next();
      System.out.println(s);
    }

  }

  public static void main(String[] args)
  {
    new JavaListTest();
  }

}

This next example is a slightly better example. In this case, because I don’t really need to know that my list is a specifically a LinkedList, I create it as a Java Collection. This is often a much more flexible solution, i.e., letting the rest of your code treat your list at the more-general Collection level instead of that code having to know that your list is really a LinkedList. Knowing that your list is really a LinkedList is an implementation detail that other developers often don’t need to know.

Here’s the next Java LinkedList example program:

package com.devdaily.javasamples;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;

public class JavaLinkedListTest2
{

  public JavaLinkedListTest2()
  {
    // LinkedList constructor; note that our reference
    // is a Collection
    Collection list = new LinkedList();
    list.add("Hello");
    list.add("world");
    
    Iterator it = list.iterator();
    while (it.hasNext())
    {
      String s = (String)it.next();
      System.out.println(s);
    }

  }

  public static void main(String[] args)
  {
    new JavaListTest2();
  }

}

Note that you can use a slightly different syntax using Java 5 and newer JVM releases. I'll provide an example for that newer syntax as soon as I can.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.