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("Qu eue 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();
}
// data = a vector
// front = the index
public int getFront()
{
if(data.size() == 0)
{
throw new NoSuchElementException("Qu
}
Integer result = (Integer) data.get(front);
front++;
if(front > 10 && front > data.size()/2)
{
data = new Vector(data.subList(front,
front = 0;
}
return result.intValue();
}
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)).int Value();
data.remove(0);
}
else
{
throw new NoSuchElementException("Qu eue underflow");
}
return (result);
}
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)).int
data.remove(0);
}
else
{
throw new NoSuchElementException("Qu
}
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.
With this method, you don't need to store (or manage) the "front" attribute.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
>> 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 ;-) ?)
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.
then the first test will be true.
It's late. Can you tell ;-) ?
The day is young here :)
that should be:
if(front>=data.size())