Link to home
Start Free TrialLog in
Avatar of azcalv408
azcalv408

asked on

array out of bound problem

I'm working on an IntQueue class and implemented a getFront() method to get the 1st element and remove it by incrementing the index. I kept getting an array out of bound error, can someone try to debug this ? thanks  (object- if you're reading this, i'm trying a new way of implementing this method)

// data = a vector
// front = the index
public int getFront()
{
       if(data.size() == 0)
       {
              throw new NoSuchElementException("Queue underflow");
       }

       Integer result = (Integer) data.get(front);
       front++;

       if(front > 10 && front > data.size()/2)
       {
                data = new Vector(data.subList(front, data.size()));
      front = 0;
       }

       return result.intValue();
}
Avatar of Mick Barry
Mick Barry
Flag of Australia image

> if(data.size() == 0)

that should be:

if(front>=data.size())
Avatar of jimmack
jimmack

I'd suggest that the two tests need combining:

if ((front >= data.size()) || (data.size() == 0))

Is there any reason why you're not simply returning the first element in the Vector, then deleting it?  eg.

public int getFront()
{
    int result = -1;

    if (data.size() > 0)
    {
        result = ((Integer)data.get(0)).intValue();
        data.remove(0);
    }
    else
    {
        throw new NoSuchElementException("Queue underflow");
    }

    return (result);
}
Sorry, I missed a bit on my last comment:

With this method, you don't need to store (or manage) the "front" attribute.
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>> this was discussed in a previous q.

Ah.

>> Second test is redundant.

If data.size() == 0, then the data.get(front) will throw an exception.  Specifically, the ArrayIndexOutOfBounds exception!

(Or was this discussed in the unreferenced question too ;-) ?)
> If data.size() == 0

then the first test will be true.
It's late.  Can you tell ;-) ?
The day is young here :)