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;
}
}
The habit may be akin to certain types of arrays in languages such as C which use null bytes to serve as terminating "sentinels" to indicate the end of an array; an example would be "C-strings", which take the form char[]
or char *
.
That being said, Java is not C, and why the author chooses to do this eludes me. It's misleading and would absolutely be considered bad practice.
Your remark on doing this to mitigate ArrayOutOfBounds
exceptions could be correct too, but creating an array of a different size than intended is not the proper way to go about it.
EDIT:
Based on the example you've given, I would say that the application for this habit of creating "misleadingly-sized" arrays is nothing more than a function of the problem that the code is designed to solve.
For instance, it's possible that the DynQueue
is being constructed this way because the first or last index represents data that is to be differentiated from the rest of the data in the array somehow... perhaps q[0]
(the first element of the queue) represents the char
that is the 'next' to be considered in some algorithm or processing (it's at the "front of the line" so to speak), but has not been cleared out of the array yet.
(That still doesn't change the fact that the way it is done is questionable.)
I don't know this book, but this example is totally misleading! Basically new int[3+1]
will initialize an int array of size 4, not 3. Given a method int[] generateArray(int size)
I would absolutely expect that it will generate an array of size passed as the argument, not a one that is size + 1. The only way the method could make any sense is naming it: generateArrayThatHasLastIndex(int lastIndex). Any other way it is wrong.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With