Reputation: 47
class MyCircularQueue {
ArrayList<Integer> CirQueue;
public MyCircularQueue(int k) {
CirQueue = new ArrayList<Integer>(k);
}
public boolean isFull() {
for(int s=0; s<this.CirQueue.size(); s++) {
if (this.CirQueue.get(s) == null) {
return false;
}
}
return true;
}
}
The isFull() method wants to return false if any index in CirQueue is null. If it iterates through the entire CirQueue ArrayList without triggering the if statement, it wants to return true. When I debug my method, however, (after initializing an ArrayList via the constructor) after setting breakpoints at the if statement, the compiler will read the for loop header, then completely skip over the if statement and simply return true. Why does this occur?
Upvotes: 0
Views: 637
Reputation: 552
Since you are using ArrayList no need to initiate it with a size k just initiate an empty ArrayList in the constructor, - you can still use your implementation too.
public MyCircularQueue() {
CirQueue = new ArrayList<Integer>();
}
ArrayList has Integer objects therefore you don't need to decide the size when initiating. Then you can proceed with your isFull() code. You still have an empty ArrayList. so you can first check whether ArrayList is empty or not before iterating over. However, even if you are initialized ArrayList with the size you don't have objects. You shaould have objects to iterate.
Upvotes: 1
Reputation: 24
Although you initialized the size of CirQueue
in the constructor, but you did not add the elements. In other words, the ArrayList
constructor ArrayList(int)
is only declare an Integer
array, but not assign to it.
I test it in JShell, CirQueue
is empty (capacity is 0, the value is []
), you should fill it by null
, this way you keep it is not empty.
Upvotes: 1
Reputation: 4070
The ArrayList
constructor with an int parameter "constructs an empty list with the specified initial capacity" (docs). That means you've got some space reserved, but the list is still empty, size()
will yield 0, and there's nothing to iterate over.
Upvotes: 4