简体   繁体   English

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

[英]What are the default values of the char array in Java?

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?有它的 ASCII 码吗? 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.谢谢。

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, '\' .对于 char 类型,默认值为空字符,即'\'

Having said that, it sounds like really you want a List<Character> , which can keep track of the actual size of the collection.话虽如此,听起来您真的想要一个List<Character> ,它可以跟踪集合的实际大小。 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:如果您需要随机访问列表(例如,即使您尚未填充元素 2,您也希望能够填充元素 25),那么您可以考虑:

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

(It's hard to know which of these is the most appropriate without knowing more about what you're doing.) (如果不了解您在做什么,就很难知道其中哪一个最合适。)

You can also convert it to int and then compare.您也可以将其转换为 int 然后进行比较。
for ex - Suppose I declare my array as例如 - 假设我将数组声明为

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

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

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