我有一个像这样的方法repeatedMethod
:
public static void repeatedMethod() {
// something else
anotherMethod("myString");
// something else
}
public static void anotherMethod(String str) {
//something that doesn't change the value of str
}
我多次调用 repeatedMethod
。
我想问一下,像这样在该方法之外将 myString
声明为 static final
是否明智:
public static final String s = "myString";
public void repeatedMethod() {
anotherMethod(s);
}
我认为当我执行 anotherMethod("myString")
时,会创建一个新的 String
实例。由于我多次这样做,因此创建了许多 String
实例。
因此,最好在 repeatedMethod
之外只创建一个 String
实例,并且每次只使用那个实例。
最佳答案
你做的是对的,但出于错误的原因。
当您执行 anotherMethod("myString")
时,实际上不会创建 String
的新实例:它可能会重用 String 常量池中的 String (引用 this question )。
但是,将常见的字符串值分解为常量(即 private static final
)是一种很好的做法:如果该常量需要更改,您只需在源代码的一个位置进行更改代码(例如,如果明天,"myString"
需要变成"myString2"
,您只需要做一个修改)
关于java - 如果我多次使用它,将 String 声明为 final 是否明智?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33451434/