java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to retrieve LinkedList objects using ListIterator?

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

package com.javacoderanch.example.util;

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

public class LinkedListListIterator {
    public static void main(String[] args) {
        List<String> grades = new LinkedList<String>();
        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