0

I am trying to implement a CircularArrayQueue and my method isEmpty() is returning false when the queue isn't populated. Can you point out my error?

public CircularArrayQueue(int size)
{
    array = new Integer[size];
    front = rear = 0;
}

... code omitted 

// returns the number of elements in the queue
@Override
public int noItems() 
{   
    return array.length - getCapacityLeft();
}

// returns true if the queue is empty
@Override
public boolean isEmpty()
{
    return noItems() == 0;
}

//returns the number of available spots in the queue before a resize needs to be done
public int getCapacityLeft()
{
    return (array.length - rear + front)%array.length;
}   
1
  • you posted the same question yesterday? Commented Mar 7, 2017 at 9:03

4 Answers 4

1

When the queue is initialised, front and rear are both zero.

public int getCapacityLeft()
{
    return (array.length - rear + front)%array.length;
} 

So getCapacityLeft returns (array.length + 0)%array.length which is zero.

You need to calculate the number of items correctly, taking into account how you manage the difference between a full buffer and an empty buffer - it seems that in both cases you are using rear == front. Decide how you will tell the difference and then you can write a getCapacityLeft which returns array.length if the buffer is empty and zero if it is full.

Sign up to request clarification or add additional context in comments.

Comments

0
return (array.length - rear + front)%array.length;

The above code, when array size is 0, getCapacityLeft will throw ArithmeticException. for not enable divide by zero.

Comments

0

try

public int getCapacityLeft(){

return array.length - Math.abs(front - rear) + 1;

}

Comments

0

try this

    if(front == -1 && rear == -1)
         return ture;
    else
         return false;

1 Comment

so... return (front == -1 && rear == -1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.