如果我多次使用它,将String声明为final是明智的吗?
发布时间:2020-12-15 04:47:05 所属栏目:Java 来源:网络整理
导读:我有一个方法重复方法,如下所示: 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} 我多次调
我有一个方法重复方法,如下所示:
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声明为静态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). 但是,将常见的String值分解为常量(即私有静态final)是一个好习惯:如果该常量需要更改,则只需要在源代码的一个位置更改它(例如,如果明天,“myString “需要成为”myString2“,你只需要做一个修改) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |