How to fix an ArrayIndexOutOfBounds Exception: -1 in ArrayDeque

142 views Asked by At

I am getting an error:

java.lang.ArrayIndexOutOfBoundsException: -1

and it refers to method inject:

deque[back] = x;

I also have methods for push and pop which add and remove items at the front but those work fine.

The idea is to use an array-based implementation as deque, where inject and eject insert item at the back and remove item at the back.

  public void inject(int x){

        if (elementCount == size){

            System.out.println("The Deque is Full");
        } else {



            deque[back] = x;            
            back = (back - 1) % size;            
            elementCount ++;

        }

    }

    public class Deque {

    int[] deque;
    int front;
    int back;
    int size;
    int elementCount;

  public Deque(int s){

           size = s;
           deque = new int[size];

           front = 1;
           back = 0;        
           elementCount = 0; //n of elements

     }

    public int getRear(){

        return deque[back];
    }   

    public int getFront(){

        return deque[front];

    }


 public void inject(int x){

            if (elementCount == size){

                System.out.println("The Deque is Full");
            } else {

                deque[back] = x;            
                back = (back - 1) % size;            
                elementCount ++;

     }

  }

   public void eject(){

            if (elementCount == 0){

                System.out.println("The deque is empty");

            }else{

                back = (back + 1) % size;
                elementCount--;
        }

    }

 }
2

There are 2 answers

0
Chai T. Rex On

You have in multiple places:

back = (back - 1) % size;

That doesn't work like you think it does when back is originally 0, where it becomes -1 % size, which is usually -1. In the places where it appears, you should instead use:

back = (size + back - 1) % size;
4
David Coler On

First thing I notice is you are using too many variables for this problem. If you break it down you only need 3 variables. the array, the size of the array and current location in the array for inject and eject. This is a LiFo( Last in First Out) order.

public void inject(int x){

    if (this.deque.size() == this.size){ //check for full array

        System.out.println("The Deque is Full");
    } else {



        this.deque[this.back+1] = x;  //input new item next slot            
        this.back ++; //increment back to new input where eject would pull from           
        }

}

public class Deque {

int[] deque;
int back;
int size;

public Deque(int s){

       this.size = s;
       this.deque = new int[size];

       this.back = 0;        
 }

this should also solve your array index issue I am not sure why you were using a Modulo function '%' for the current location of back.