java Java中char数组的默认值是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35620464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 00:22:02  来源:igfitidea点击:

What are the default values of the char array in Java?

javaarrayschar

提问by user1090944

If I allocate array of characters like this:

如果我分配这样的字符数组:

char[] buffer = new char[26];

what are the default values it is allocated with? I tried to print it and it is just an empty character.

分配给它的默认值是什么?我试图打印它,它只是一个空字符。

System.out.println("this is what is inside=>" + buffer[1]);

this is what is inside=>

Is there an ASCII code for it? I need to be able to determine if the array is empty or not, and further on, when I fill say first five elements with chars, I need to find out that the sixth element is empty. Thanks.

有它的 ASCII 码吗?我需要能够确定数组是否为空,并且进一步,当我用字符填充前五个元素时,我需要找出第六个元素是空的。谢谢。

回答by Jon Skeet

It's the same as for any type: the default value for that type. (So the same as you'd get in a field which isn't specifically initialized.)

它与任何类型相同:该类型的默认值。(所以与您在未专门初始化的字段中得到的相同。)

The default values are specified in JLS 4.12.5:

JLS 4.12.5中指定了默认值:

For type char, the default value is the null character, that is, '\u0000'.

对于 char 类型,默认值为空字符,即'\u0000'.

Having said that, it sounds like really you want a List<Character>, which can keep track of the actual size of the collection. If you need random access to the list (for example, you want to be able to populate element 25 even if you haven't populated element 2) then you could consider:

话虽如此,听起来您真的想要一个List<Character>,它可以跟踪集合的实际大小。如果您需要随机访问列表(例如,即使您尚未填充元素 2,您也希望能够填充元素 25),那么您可以考虑:

  • A Character[]using nullas the "not set" value instead of '\u0000'(which is, after all, still a character...)
  • A Map<Integer, Character>
  • Sticking with char[]if you know you'll never, ever, ever want to consider an element with value '\u0000'as "set"
  • A Character[]usingnull作为“未设置”值而不是'\u0000'(毕竟,这仍然是一个字符......)
  • 一个 Map<Integer, Character>
  • 坚持,char[]如果你知道你永远,永远,永远想考虑一个元素的价值'\u0000'为“设置”

(It's hard to know which of these is the most appropriate without knowing more about what you're doing.)

(在不了解您正在做什么的情况下,很难知道其中哪一个最合适。)

回答by Ashray Aman

You can also convert it to int and then compare.
for ex - Suppose I declare my array as

您也可以将其转换为 int 然后进行比较。
例如 - 假设我将数组声明为

char[] arr = new char[10];
arr[3]='1';

Then, the below code

然后,下面的代码

for(char c:arr){
    if((int)c!=0){
        System.out.println(c);
    }
}

Will output

会输出

1