patternjavaMinor
Queue implementation using arrays
Viewed 0 times
implementationqueueusingarrays
Problem
Please review the code:
package com.gmail.practice;
import java.util.Arrays;
public class Queues {
int head;
int tail;
int size;
int[] queue;
public Queues(int arraysize)
{
if(arraysize<0)
{
throw new IllegalArgumentException("size cannote be less than equals zero");
}
head = -1;
tail = -1;
size = arraysize;
queue = new int[size];
}
public boolean isEmpty()
{
return(tail == -1 && head == -1);
}
public void enqueue(int value)
{
if((tail+1)%size == head)
{
System.out.println("the queue is full");
}else if(isEmpty())
{
head++;
tail++;
queue[tail] = value;
}else{
tail = (tail+1)%size;
queue[tail] = value;
}
}
public int dequeue()
{
int value = 0;
if(isEmpty())
{
System.out.println("the queue is empty cant dequeue");
}else if(tail == head){
value = queue[head];
head = -1;
tail = -1;
}else{
value = queue[head];
head = (head+1)%size;
}
return value;
}
public void display()
{
System.out.println(Arrays.toString(queue) + " " + "tail is " + " "+ tail +" the head is" + " " + head);
}
public static void main(String[] args)
{
Queues q = new Queues(5);
q.enqueue(3);
q.enqueue(4);
q.enqueue(2);
q.enqueue(1);
q.enqueue(5);
q.display();
q.dequeue();
q.dequeue();
q.display();
q.enqueue(1);
q.enqueue(5);
q.dequeue();
q.dequeue();
}
}Solution
- I think the value variable in the dequeue method is potentially destructive. Rather than printing "the queue is empty cant dequeue", and returning the default value of the value variable, I think it's better to throw an exception and catch it. An example on why it is destructive:
if(q.dequeue() == 5) // this will return 0 if the array is empty.This is not good. The user will think the value that is being returned is 0, though it's already empty.
- You initialized the size variable, but you didn't really do anything to it in your queue operations (E.G. size-1 when you dequeue an item). It doesn't make sense for the size variable to not change if you enqueue/dequeue items from the queue. But I'm not sure why it's there yet you don't have a size() method. If you're not going to implement a size method (you should), I think the size variable is useless.
- I think it would be more flexible if the array is resizeable (E.G. size*2 if full, size/4 if too large).
- Make it generic so you can add other types.
Code Snippets
if(q.dequeue() == 5) // this will return 0 if the array is empty.Context
StackExchange Code Review Q#106535, answer score: 6
Revisions (0)
No revisions yet.