也许我只是疯了,或者也许我忘记了事情应该如何运作。但我在追查一个错误(同时学习一些 Groovy)并发现以下断言失败。我想我认为当使用字符串文字时,会为其创建一个新的 String 实例。我错了吗?
String one = 'one'
String two = 'one'
// I thought this should fail, but it doesn't
assert one.is(two) == false
one = new String("one")
two = new String("one")
// This works as expected
assert one.is(two) == false
通过使用dump()方法,我可以看到它们确实是同一个String实例。任何帮助或指导将不胜感激。
谢谢!
最佳答案
当你使用字符串文字时,Java 允许它们被保留,所以你得到相同的实例..
section 2.3 in the VM spec提到了这一点。
String literals and, more generally, strings that are the values of constant expressions are "interned" so as to share unique instances, using the method String.intern.
Groovy 也遵循这个规则
关于groovy - 创建字符串文字并期待一个新实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12006538/