Java 初始化字符数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19206360/
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-08-12 15:01:47  来源:igfitidea点击:

Initialize character array

javaarrays

提问by Shumail

I am just new to Java and I am struck in my program with Array initialization because it's not working and contains some garbage. This is what I am doing:

我刚接触 Java,我对我的程序中的 Array 初始化感到震惊,因为它不起作用并且包含一些垃圾。这就是我正在做的:

char[] expArray = new char[expEv.length];   //expEv.length is int - expEv is another array
//I have tried all following but not working

expArray = {'
getClass().getName() + '@' + Integer.toHexString(hashCode()) 
'}; // error i get: Array constants can only be used in initializers expArray = {'',}; expArray = {'
System.out.println(Arrays.toString(expArray ));
'}; System.out.println("array value: " + expArray); // prints " array value: [C@1cd761a "

Edit:I have also tried to use char[] expArray = new char[expEv.length] {'\0'};but this doesn't work as

编辑:我也尝试使用,char[] expArray = new char[expEv.length] {'\0'};但这不起作用

Please help me with this and explain the array initialization for the context.

请帮我解决这个问题并解释上下文的数组初始化。

回答by btse

The suggestion that these people are giving you is incorrect since I bet you still want to create a variable sized array. In fact, what you are currently doing is 100% fine.

这些人给你的建议是不正确的,因为我打赌你仍然想创建一个可变大小的数组。事实上,你目前正在做的事情是 100% 好的。

Java automatically initializes variables that are not explicitly set. In your case, each value of your array is initialized to the null character. Hereis what each variable type will be initialized to.

Java 会自动初始化未显式设置的变量。在您的情况下,数组的每个值都初始化为空字符。是每个变量类型将被初始化的内容。

The only reason you are getting gibberish when printing like that is because Java's built in toString()is not doing what you're expecting. Here is what the built-in toString()is actually returning:

像这样打印时出现胡言乱语的唯一原因是因为 Java 的内置toString()功能没有按照您的预期运行。这是内置toString()函数实际返回的内容:

char[] expArray = {'##代码##'};
expArray = java.util.Arrays.copyOf(expArray, expEv.length);

If you really want to print the array's values then you need to do something like this:

如果你真的想打印数组的值,那么你需要做这样的事情:

##代码##

回答by Dolda2000

Sorry, but Java just doesn't allow you to do that. However, this may be close enough:

抱歉,Java 不允许您这样做。但是,这可能足够接近:

##代码##

Though, in the case of initializing the array with a '\0', that is completely unnecessary, since the array creation itself will clear all the elements to zero.

但是,在使用 a 初始化数组的情况下'\0',这是完全没有必要的,因为数组创建本身会将所有元素清除为零。