简体   繁体   English

在Java中,使用null字符更改char数组的大小

[英]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. 下面的代码(摘自Gaale Laakman的“ Cracking the代码访谈”)展示了如何在不使用数组副本的情况下删除char数组中的重复字符,从而避免了额外的内存使用。 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? 还是这只是一个示例,我们将检查空字符在哪里查找数组的长度,而不使用有问题的length变量?

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;
    }

It sounds like a question that has been translated from C or C++. 听起来好像是从C或C ++翻译过来的问题。 In those langauges you use a null character for the end of a string (which in turn is a char array). 在这些语言中,您在字符串的末尾使用一个空字符(而该char又是一个char数组)。 In Java this does not work; 在Java中,此方法无效。 the array never changes its length. 数组永远不会改变其长度。

If the caller knows that this null character is inserted, they can use the information of course, and ignore characters after the null. 如果呼叫者知道已插入此空字符,则他们当然可以使用该信息,并忽略该空字符之后的字符。 They cannot use the len variable since this only lives inside the method and does not exist when the method returns. 他们不能使用len变量,因为它仅存在于方法内部,并且在方法返回时不存在。

In Java you would usually do: 在Java中,您通常会执行以下操作:

str = Arrays.copyOf(str, tail);

This would create a new array the right length and copy all the characters (which is what the code example aimed at avoiding). 这将创建一个正确长度的新数组并复制所有字符(这是代码示例旨在避免的字符)。

By the way, I get an ArrayIndexOutOfBoundsException in the line str[tail] = 0; 顺便说一句,我在str[tail] = 0;行中得到了ArrayIndexOutOfBoundsException str[tail] = 0; in the end if no duplicates were found. 最后如果没有发现重复。 In this case tail is equal to the length of the array and therefore 1 position beyond the last element. 在这种情况下, tail等于数组的长度,因此比最后一个元素高1个位置。

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. 当它们的循环达到零时,它知道它在数组的概念“末端”。

Array are immutable so the length does not change the empty space is filled with null values 数组是不可变的,因此长度不会改变,空白区域会填充空值

public class MainClass {

public static void main(String[] args) {
char[] org={'a','b','b','c'};
System.out.println(org.length);
System.out.println(org);
removeDuplicate(org);
System.out.println(org.length);
   System.out.println(org);

}
public static void removeDuplicate(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;
  }
 }

**Results**
   4
  abbc
   4
  abc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM