gpt4 book ai didi

java - 这个 Java String 数组声明有什么问题 - 非常奇怪

转载 作者:行者123 更新时间:2023-12-02 11:16:44 24 4
gpt4 key购买 nike

我有三种不同的方式在 Java 中声明我的字符串数组。其中一个始终有效,但另外两个仅根据写入顺序起作用。

在第一个版本中,方法2不起作用,但方法3起作用。

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...?)

但是,交换位置和工作声明也会交换。看,现在方法2可以工作,但方法3不行。

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...?)

最佳答案

尝试这样做,让它按照您的预期工作:

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 '}'
}

这些“{…}” block 是初始化 block ,更广为人知/更常在其静态变体中使用,如 的“static {…}”静态最终 属性。这是因为这些初始化程序中的代码通常最好放入构造函数中。

使用这些初始化程序的优点是它们在所有构造函数之前执行,缺点是它们在所有构造函数之前执行。当您使用 final 属性时效果最好......

它们适用于所有常量初始化(如此处的示例)以及其他类型(可能)永不失败的初始化。应避免从此处调用非静态方法,并且调用当前类的非静态方法根本不起作用(this 尚未初始化,因为您当前正在初始化它......)。

关于java - 这个 Java String 数组声明有什么问题 - 非常奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60682660/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com