CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Collections

Collections and Generics
LinkedList class
Generic queue

Using a linked list to implement a generic queue

  • A queue is a first-in, first-out collection. To implement a queue, you can use a linked list.
  • A class that implements a queue is typically declared with a type variable that's used to specify the type of objects the queue will hold.

Basic methods of a class that implements a generic queue

Method Description
push(element) Adds the specified element to the end of the queue.
pull() Retrieves and removes an element from the front of the queue.
size() Returns the number of elements in the queue.

A GenericQueue class that implements a queue

import java.util.LinkedList;

public class GenericQueue
{
    private LinkedList list = new LinkedList();

    public void push(E item)
    {
        list.addLast(item);
    }

    public E pull()
    {
        return list.removeFirst();
    }

    public int size()
    {
        return list.size();
    }
}

Code that uses the GenericQueue class

GenericQueue q1 = new GenericQueue();
q1.push("Item One");
q1.push("Item Two");
q1.push("Item Three");
System.out.println("The queue contains " + q1.size()
    + " items");
while (q1.size > 0)
    System.out.println(ql.pull());
System.out.println("The queue now contains " + ql.size()
    + " items");

Resulting output

The queue contains 3 items
Item One
Item Two
Item Three
The queue now contains 0 items
Previous | Class | Code | Chain of nodes | Stacks and Queues | Generic queue | ArrayList and LinkedList | Next