Implementing Queue in Java

 

Queue is a First-In-First-Out (FIFO) data structure. In a FIFO data structure, the first element added to the queue will be the first to be removed. Suppose if a queue contains 4 elements and 5th element added at back and if we need to remove that element then we need to remove all front 4 elements first. As like Stack implementation in java we can implement Queue Data Structure and also we have operations in Queue like enqueue(), dequeue(), front(), isempty() etc.,
Implementing Queue in Java

enqueue() - Insert element in front of the Queue.

dequeue() - Return front element and remove same element from the Queue.

front() - Same as dequeue() returns front element but same element won't be removed from the Queue.

clean() - cleans the Queue.



Lets see simple example to implement Queue using ArrayList and using Generics for holding any datatype.



import java.util.ArrayList;
import java.util.List;

public class MyQueue <E>{

 private List<E> list = null;
 
 public MyQueue() {
  list = new ArrayList<E>();
 }

 public void enqueue(E val){
  list.add(val);
 }
 
 public E dequeue(){
  E val = null;
  if(list.size() > 0){
   val = list.get(0);
   list.remove(0);
  }  
  return val;
 }
 
 public boolean isEmpty(){
  if(list.size() == 0)return true;
  else return false;
 }
 
 public int size(){
  return list.size();
 }
 
 public E front(){
  E val = null;
  if(list.size() > 0){
   val = list.get(0);
  }  
  return val;
 }
 
 public void clean(){
  list = new ArrayList<E>();
 }
 
 @Override
 public String toString() {
  return list.toString();
 }
}


Our Queue class is ready and we can test with below code.


public class TestMyQueue {

 public static void main(String[] args) {
  
  MyQueue<String> queue = new MyQueue<String>();
  
  int qSize = queue.size();
  System.out.println("QUEUE SIZE : "+qSize);
  
  //ENQUEUE
  queue.enqueue("one");
  queue.enqueue("two");
  queue.enqueue("three");
  queue.enqueue("four");
  queue.enqueue("five");
  System.out.println("5 ELEMENTS ADDED IN QUEUE");
  qSize = queue.size();
  System.out.println("QUEUE SIZE : "+qSize);
  
  //QUEUE
  System.out.println("QUEUE      : "+queue);
  
  //FRONT
  System.out.println("FRONT       : "+queue.front());
  
  //DEQUEUE
  System.out.println("DEQUEUE        : "+queue.dequeue());
    
  qSize = queue.size();
  System.out.println("QUEUE SIZE : "+qSize);
  
  //FRONT
  System.out.println("FRONT       : "+queue.front());
  
  //ISEMPTY
  System.out.println("EMPTY      : "+queue.isEmpty());
  
  //CLEAN
  queue.clean();
  System.out.println("QUEUE CLEANED");
  
  //ISEMPTY
  System.out.println("EMPTY      : "+queue.isEmpty());
  
 }
}


OUTPUT:


QUEUE SIZE     : 0
5 ELEMENTS ADDED IN QUEUE
QUEUE SIZE     : 5
QUEUE             : [one, two, three, four, five]
FRONT             : one
DEQUEUE         : one
QUEUE SIZE      : 4
FRONT             : two
EMPTY             : false
QUEUE CLEANED
EMPTY             : true






No comments:
Write comments