我在一个软件中看到了一些旧的代码片段,没有人记得是谁写的,而不是做类似的事情:
String abc = SOME_CONSTANT.toLowerCase()
他们这样做:
String abc = new String(SOME_CONSTANT).toLowerCase()
我看不出任何有价值的东西 - 看起来像是简单的旧编程(例如,不理解String是不可变的)。任何人都可以看到良好的原因吗?
注意: SOME_CONSTANT定义为 -
public static final String SOME_CONSTANT = "Some value";
答案 0 :(得分:4)
不,它只会创建更多对象(除非编译器将其优化掉)
答案 1 :(得分:3)
我同意你的观点:这是糟糕的编程
答案 2 :(得分:3)
没有充分的理由。正如你所说,String是不可变的,所以在它上面调用toLowerCase()
总会产生一个新的字符串。
答案 3 :(得分:3)
将String包装在另一个String中的唯一要点是强制复制。 e.g。
String str = "A very very log string .......";
// uses the same underlying string which we might not need after this.
String str1 = str.substring(0, 1);
// take a copy of which only has one char in it.
String str2 = new String(str1);
我会做的
public static final String SOME_CONSTANT = "Some value";
public static final String LOWER_CONSTANT = SOME_CONSTANT.toLowerCase();
答案 4 :(得分:0)
new String(someString)
只在一个重要案例中才有意义:
String s = incredilyLongString.substring(1000,1005);
String t = new String(s);
假设令人难以置信的LongString是1000000个字符长(例如一个XML文件),你只需要5个字符。 String仍将至少占用一个MEGABYTE内存,但String t将从头开始创建,因此只占用必要的内存。
答案 5 :(得分:0)
我不确定,但我认为当你使用new String()
时,你强制JVM为该String创建一个新对象。如果您使用SOME_CONSTANT.toLowerCase()
,JVM将在字符串池中搜索,如果存在相同的字符串,则仅提供引用。
在这种情况下使用new String()
可能是一个很好的做法,只是为了明确toLowerCase()
只影响生成的新String,而不是常量。
但无论如何,效果是一样的