javaarrayscharvariable-lengthnull-character

in java, change size of char array with null character


The following code (from "Cracking the code interview", from Gaale Laakman), shows how to remove duplicate characters in a char array without using a copy of the array to avoid some extra memory use. It re-writes the final characters in the first array with an offset. Since the final array is smaller than the previous one, a null character is set at the position following the final characters, as if to say the array stops there:

    str[tail] = 0;

I was wondering if by doing this the variable "length" of the array gets changed. If not, I don't understand why this example works. Or is this just an example where we would check where is the null character to find the length of the array and don't use the length variable in question?

Here is the whole code:

    public static void removeDuplicates(char[] str) {
        if (str == null) return;
        int len = str.length;
        if (len < 2) return;
        int tail = 1;
        for (int i = 1; i < len; ++i) {
            int j;
            for (j = 0; j < tail; ++j) {
                if (str[i] == str[j]) break;
            }
            if (j == tail) {
                str[tail] = str[i];
                ++tail;
            }
        }
        str[tail] = 0;
    }

Solution

  • An array has a fixed length on creation. In the example they want to save some time by always re-using the same array for every iteration. As it is not possible to shrink the array (as the length is determined on creation), they use a work around, they put a zero at the place where the array should end. When their loop reaches the zero, it knows it is at the conceptual 'end' of the array.