【问题标题】:String Objects Equality [duplicate]字符串对象相等[重复]
【发布时间】:2016-04-12 05:39:53
【问题描述】:

为什么在使用相等运算符'=='比较时,使用具有相同字符串文字的String类构造函数声明的两个字符串对象不相等,但通过分配相同的字符串文字直接声明时是相等的。

String s1 = new String("hello");
String s2 = new String("hello");
Boolean result1 = (s1 == s2);// returns false

String s3 = "hello";
String s4 = "hello";
Boolean result2 = (s3 == s4);// returns true

【问题讨论】:

  • 这个答案是对该问题的最佳解释......

标签: java string


【解决方案1】:

s1 和 s2 是 2 个不同的对象,所以引用不相等

在 s3 期间,在字符串池中创建对象,在 s4 期间没有创建新对象,因为 hello 已经存在。所以 s4 只指向 hello 对象存在池。

因为现在 s3 和 s4 都指向同一个对象,所以引用是相同的。

如您所知 == 检查引用,使其返回 true

【讨论】:

  • 完全没有必要。请投票以适当的副本结束。
猜你喜欢
  • 2018-10-16
  • 2011-03-17
  • 2015-01-05
  • 2014-07-19
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 2017-06-20
相关资源
最近更新 更多