获取编译器错误,而在构造函数中使用数组常量 [英] Getting compiler error while using array constants in the constructor
问题描述
public class Sonnet29 implements Poem {
private String[] poem;
public Sonnet29() {
poem = { "foo", "bar" , "baz"};
}
@Override
public void recite() {
//...
}
}
行诗= {富,酒吧,巴兹};
是给编译错误
任何具体原因这是不允许的?
我如何初始化字符串数组与数组常量?
Any specific reason why this is not allowed? How do I initialize a String array with array constants?
编辑:谢谢你的乡亲对你的答案。现在我很清楚什么是允许的,哪些不是。
但是,我可以问你的为什么这是不允许的?
Thank you folks for your answers. Now I'm clear what is allowed and what is NOT. But can I ask you why this is NOT allowed?
String[] pets;
pets = {"cat", "dog"};
google搜索了一下后,我发现这链接,其中,被告知,编码这样的叶子在模糊的编译器 - 宠物是否应该是一个字符串数组或对象数组。不过从声明中,它可以很好地弄清楚,它是一个字符串数组,正确的?
After googling a bit, I found this link, where in, it is told that coding like this leaves the compiler in ambiguity - whether the pets should be array of Strings or array of Objects. However from the declaration, it can very well figure out that it is a String array, right???
推荐答案
这会做你要找的内容:
public Sonnet29() {
poem = new String[] { "foo", "bar", "baz" };
}
创建阵列的新实例初始化时,列表是只允许。
Initialization lists are only allowed when creating a new instance of the array.
这篇关于获取编译器错误,而在构造函数中使用数组常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!