Initializing Java Array Size

I read the book “Java: A Beginners Guide (5th Edition)” by Herbert Schildt, and I continue to notice a special method for declaring arrays.

Here is 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 does this author do, ALWAYS create an array with +1up to size. I don’t understand why he will do it. Should we avoid exceptions ArrayOutOfBounds? Also, why not just send 4 instead of 3 if it is already going to increase it by 1?

Here is an example from his book to find out 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;
    }
}
+4
source share
2 answers

, ! new int[3+1] int 4, 3. int[] generateArray(int size), , , , , + 1. , , : generateArrayThatHasLastIndex (int lastIndex). .

+4

, C, , "", ; "C-strings" , char[] char *.

, Java C, , . .

ArrayOutOfBounds , , , .

EDIT:

, " " - , , .

, , DynQueue , , ... q[0] ( ) the char, "", (, , " " ), .

( , , , .)

+4

All Articles