CIS 35A: Introduction to Java Programming

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

Collections

Collections and Generics
LinkedList class
Stacks and Queues

A stack can be viewed as a special type of list, where the elements are accessed, inserted, and deleted only from the end, called the top, of the stack.

A stack is called a Last-In First-Out (LIFO) list because the last item pushed onto a stack is always the first item popped from the task.

A queue represents a waiting list. A queue can be viewed as a special type of list, where the elements are inserted into the end (tail) of the queue, and are accessed and deleted from the beginning (head) of the queue.

A queue is called a FIFO list - First In, First out.

Since the insertion and deletion operations on a stack are made only the end of the stack, using an array list to implement a stack is more efficient than a linked list. Since deletions are made at the beginning of the list, it is more efficient to implement a queue using a linked list than an array list.

Design of the Stack and Queue Classes

There are two ways to design the stack and queue classes:
  • Using inheritance: You can declare the stack class by extending the array list class, and the queue class by extending the linked list class.
  • Using composition: You can declare an array list as a data field in the stack class, and a linked list as a data field in the queue class.

Both designs are fine, but using composition is better because it enables you to declare a complete new stack class and queue class without inheriting the unnecessary and inappropriate methods from the array list and linked list.

Previous | Class | Code | Chain of nodes | Stacks and Queues | Generic queue | ArrayList and LinkedList | Next