I'm reading a book "Java: A Beginners Guide (5th Edition)" by Herbert Schildt and I keep noticing a peculiar method of declaring arrays.
Here's my own example to personify this practice:
public int[] generateArray(int size) {
int[] x = new int[size+1];
return x;
}
int[] y = generateArray(3);
Now, what this author is doing is ALWAYS creating the array with +1 to the size. I do not understand why he would do this. Is it avoiding ArrayOutOfBounds exceptions? Furthermore, why not just send in 4 instead of 3 if he's already going to increment it by 1?
Here's an example from his book to clear up the ambiguity of this question:
// A dynamic queue.
class DynQueue implements ICharQ {
private char q[];
private int putLoc, getLoc;
public DynQueue(int size) {
q = new char[size+1]; //allocate memory
putLoc = getLoc = 0;
}
}