我的问题是
Java处理字符串的方式.从
Java语言规范(JLS)中可以清楚的说,字符串文字被隐式地嵌入 – 换句话说,是在堆的String常量池部分中创建的对象,与在调用新字符串时创建的基于堆的对象相反(“随你”).
什么似乎不符合JLS所说的那样,当使用String连接与一个转换的常量String类型创建一个新的String时,它应该被视为一个JLS的常量String,显然JVM正在创建一个新的字符串对象,而不是隐含地实现它.我感谢关于这个特定行为的任何解释,以及这是否是平台特定的行为.我在Mac OSX Snow Leopard上运行.
public class Test { public static void main(String args[]) { /* Create a String object on the String constant pool using a String literal */ String hello = "hello"; final String lo = "lo"; // this will be created in the String pool as well /* Compare the hello variable to a String constant expression,that should cause the JVM to implicitly call String.intern() */ System.out.println(hello == ("hel" + lo));// This should print true /* Here we need to create a String by casting an Object back into a String,this will be used later to create a constant expression to be compared with the hello variable */ Object object = "lo"; final String stringObject = (String) object;// as per the JLS,casted String types can be used to form constant expressions /* Compare with the hello variable */ System.out.println(hello == "hel" + stringObject);// This should print true,but it doesn't :( } }
解决方法
在编译时常数表达式中不允许转换为对象.唯一允许的演员是String和原语. JLS(Java SE 7版)第15.28节:
> – Casts to primitive types and casts to type String
(实际上有第二个原因,对象不是最终的,所以不可能考虑一个constant variable.“原始类型或类型String的变量,即最终的,并且使用编译时常量表达式(§15.28)初始化,称为常数变量“ – 第4.12.4节)