在构造函数中使用数组常量时遇到编译器错误 [英] 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(){
// ...
}
}
行 poem = {foo,bar,baz};
给出编译错误。
为什么不允许这样做的任何特定原因?
如何用数组常量初始化一个字符串数组?
编辑:谢谢你的答案。现在我清楚什么是允许的,什么是不。
但是我可以问你为什么不允许这样做吗?
;
pets = {cat,dog};
在google了一下后,我发现这个 link ,其中,通知这样的编码会使编译器模糊宠物应该是数组的字符串或对象数组。但是从声明,它可以很好地弄清楚,它是一个字符串数组,对吗?
这将满足您的需求:
public Sonnet29(){
poem = new String [] {foo,bar,baz};
}
仅当创建数组的新实例时才允许初始化列表。 p>
public class Sonnet29 implements Poem {
private String[] poem;
public Sonnet29() {
poem = { "foo", "bar" , "baz"};
}
@Override
public void recite() {
//...
}
}
Line poem = { "foo", "bar" , "baz"};
is giving compilation error.
Any specific reason why this is not allowed? How do I initialize a String array with array constants?
EDIT: 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"};
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???
This will do what you're looking for:
public Sonnet29() {
poem = new String[] { "foo", "bar", "baz" };
}
Initialization lists are only allowed when creating a new instance of the array.
这篇关于在构造函数中使用数组常量时遇到编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!