我用三种不同的方式在Java中声明字符串数组。一种始终有效,而另两种仅根据其写入顺序起作用。
在第一个版本中,method2不起作用,但method3起作用。
public class weirdStringArray {
String [] method1 = new String [] {"one","two","three"}; //<------ Works no matter where it's placed
String [] method2; //<------ "Syntax error on token ";", { expected after this token"
method2 = new String[3]; // Doesn't work in this postion
method2[0] = "one";
method2[1] = "two";
method2[2] = "three";
String [] method3 = new String[3]; //<------- No issue, works fine in this position
method3[0] = "one";
method3[1] = "two";
method3[2] = "three";
} // <----- Syntax error, insert "}" to complete ClassBody (but it does seem to complete ClassBody...?)
但是,开关位置和工作声明也会互换。看,现在method2可以使用,但method3不能。
public class weirdStringArray {
String [] method1 = new String [] {"one","two","three"};
String [] method3 = new String[3]; //<------ "Syntax error on token ";", { expected after this token"
method3[0] = "one"; // Doesn't work in this postion
method3[1] = "two";
method3[2] = "three";
String [] method2; //<---------- Put it in a different place and it works
method2 = new String[3];
method2[0] = "one";
method2[1] = "two";
method2[2] = "three";
} // <----- Syntax error, insert "}" to complete ClassBody (but it does seem to complete ClassBody...?)
这里可能会发生什么?为什么顺序会有所不同?位置2发生了什么?顺便说一句,如果我删除第一个工作表格,这没有什么区别:
public class weirdStringArray {
//String [] method1 = new String [] {"one","two","three"};
String [] method2; //<------ "Syntax error on token ";", { expected after this token"
method2 = new String[3]; // Doesn't work in this postion
method2[0] = "one";
method2[1] = "two";
method2[2] = "three";
String [] method3 = new String[3]; //<------- No issue, works fine in this position
method3[0] = "one";
method3[1] = "two";
method3[2] = "three";
} // <----- Syntax error, insert "}" to complete ClassBody (but it does seem to complete ClassBody...?)
问题来源:Stack Overflow
尝试以下操作以使其按预期运行:
public class weirdStringArray {
String [] method1 = new String [] {"one","two","three"}; //<-- Works no matter where it's placed, because this is a valid one line initialisation
String [] method2;
{
// We gave it the '{' the compiler asked for …
method2 = new String[3];
method2[0] = "one";
method2[1] = "two";
method2[2] = "three";
}
String [] method3 = new String[3];
{
method3[0] = "one";
method3[1] = "two";
method3[2] = "three";
} // <-- … and this is the missing '}'
}
这些' {…}'块是初始化块,在其静态变量中更广为人知/经常使用,作为属性的' static {…}' static final。这是因为通常将这些初始化程序中的代码更好地放入构造函数中。
使用这些初始化程序的优点是它们在所有构造函数之前执行,而缺点是在所有构造函数之前执行。当您使用final属性时最好看……
它们适用于所有恒定的初始化,例如此处的示例,以及其他类型的(可能)永不失败的初始化。应该避免从此处调用非静态方法,并且根本无法调用当前类的非静态方法(this尚未初始化,因为您正在初始化它……)。
回答来源:Stack Overflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。