How do I retrieve LinkedList objects using ListIterator?

This example show you how to use the ListIterator interface to retrieves objects from a LinkedList.

package org.kodejava.example.util;

import java.util.List;
import java.util.LinkedList;
import java.util.ListIterator;

public class LinkedListListIterator {
    public static void main(String[] args) {
        List grades = new LinkedList();
        grades.add("A");
        grades.add("B");
        grades.add("C");
        grades.add("D");
        grades.add("E");

        //
        // Retrieves object from LinkedList using the ListIterator
        // interface.
        //
        ListIterator li = grades.listIterator();
        while (li.hasNext()) {
            System.out.println("Grades: " + li.next());
            System.out.println("    hasPrevious  : " + li.hasPrevious());
            System.out.println("    hasNext      : " + li.hasNext());
            System.out.println("    previousIndex: " + li.previousIndex());
            System.out.println("    nextIndex    : " + li.nextIndex());
        }
    }
}

The program will prints the following output:

Grades: A
    hasPrevious  : true
    hasNext      : true
    previousIndex: 0
    nextIndex    : 1
Grades: B
    hasPrevious  : true
    hasNext      : true
    previousIndex: 1
    nextIndex    : 2
Grades: C
    hasPrevious  : true
    hasNext      : true
    previousIndex: 2
    nextIndex    : 3
Grades: D
    hasPrevious  : true
    hasNext      : true
    previousIndex: 3
    nextIndex    : 4
Grades: E
    hasPrevious  : true
    hasNext      : false
    previousIndex: 4
    nextIndex    : 5

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply