You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java String对象创建疑惑:toUpperCase后hashCode相同但==判断为false

Why hashCode() is the same but == returns false for these Strings?

Great question! Let's break this down clearly so you understand exactly what's happening here.

First, let's recap two critical Java concepts that are key to this behavior:

  • The == operator for object types (like String) compares object references, not the content of the objects. It only returns true if both variables point to the exact same object instance in memory.
  • The hashCode() method follows a core rule: if two objects are equal (as per the equals() method), they must have the same hashCode(). However, the reverse isn't true—two different objects can absolutely have the same hashCode() (this is called a hash collision), though in your case, the objects actually have identical content.

Now let's walk through your code step by step:

  1. String s8 = "abcd"; creates a string in the string constant pool (a special area of memory for reusing string literals).
  2. When you call s8.toUpperCase(), the String class's implementation of this method creates a new String object in the heap (not the constant pool) containing the uppercase version "ABCD". There's no caching here—every time you call toUpperCase() on the same original string, it generates a brand new object instance, even if the content is identical.
  3. So s9 and s11 are two separate String objects, both holding "ABCD", but living at different memory addresses.

That's why:

  • s9.hashCode() and s11.hashCode() are the same: String's hashCode() is calculated based on the string's content. Since both have "ABCD", their hash values match perfectly.
  • s9 == s11 returns false: because == checks if the variables point to the same object, and these are two distinct instances.

If you wanted == to return true here, you could use the intern() method, which adds the string to the constant pool (or returns an existing reference if it's already there):

String s9 = s8.toUpperCase().intern();
String s11 = s8.toUpperCase().intern();
System.out.println(s9 == s11); // This would print true

内容的提问来源于stack exchange,提问作者Kunu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:04:35