我的问题是关于 Java 处理字符串文字的方式。从 Java 语言规范 (JLS) 可以清楚地看出,字符串文字是隐式驻留的 - 换句话说,在堆的字符串常量池部分中创建的对象,与调用时创建的基于堆的对象形成对比new String("whatever")
.
似乎与 JLS 所说的不一致的是,当使用 String 连接与强制转换的常量 String 类型创建新的 String 时,根据 JLS 应将其视为常量 String,显然 JVM 正在创建一个新的 String String 对象而不是隐式地实习它。我很欣赏有关此特定行为以及这是否是特定于平台的行为的任何解释。我正在 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 :(
}
}
投射到Object
不允许出现在编译时常量表达式中。唯一允许的强制转换是String
和基元。 JLS(Java SE 7 版)第 15.28 节:
> - 转换为原始类型并转换为 String 类型 http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.28
(实际上还有第二个原因。object
isn't final
所以不可能被认为是常数变量 http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.4。 “原始类型或类型的变量String
, 那是final
并用编译时常量表达式(第 15.28 节)进行初始化,称为常量变量。”——第 4.12.4 节。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)