奇怪的字符串池行为 [英] Strange String pool behavior

查看:149
本文介绍了奇怪的字符串池行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的字符串池行为的问题。
我正在使用 == 来比较相等的字符串,以确定它们是否在池中。

I've got a question of some strange String pool behavior. I'm using == to compare equal Strings to find out whether they're in the pool or not.

public class StringPoolTest {
  public static void main(String[] args) {
    new StringPoolTest().run();
  }

  String giveLiteralString() {
    return "555";
  }

  void run() {
    String s1 = giveLiteralString() + "";
    System.out.println("555" == "555" + "");
    System.out.println(giveLiteralString() == giveLiteralString() + "");
  }
}

输出为:

true
false



<对我来说这是一个很大的惊喜。有人能解释一下吗?
我认为这个问题发生在编译时。但为什么在String中添加会产生任何差异?

推荐答案

"555" + ""

是< a href =http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.28>编译时常量,而

giveLiteralString() + ""

不是。因此,前者只编译为字符串常量555,后者编译成实际的方法调用和连接,从而产生一个新的String实例。

isn't. Therefore the former compiles into just the string constant "555" and the latter compiles into the actual method invocation and concatenation, resulting in a fresh String instance.



另见JLS§3.10.5(字符串文字)


在运行时通过串联计算的字符串是新创建的,因此
是不同的。

Strings computed by concatenation at run time are newly created and therefore distinct.

这篇关于奇怪的字符串池行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆