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 (likeString) compares object references, not the content of the objects. It only returnstrueif 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 theequals()method), they must have the samehashCode(). However, the reverse isn't true—two different objects can absolutely have the samehashCode()(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:
String s8 = "abcd";creates a string in the string constant pool (a special area of memory for reusing string literals).- When you call
s8.toUpperCase(), theStringclass's implementation of this method creates a newStringobject in the heap (not the constant pool) containing the uppercase version "ABCD". There's no caching here—every time you calltoUpperCase()on the same original string, it generates a brand new object instance, even if the content is identical. - So
s9ands11are two separateStringobjects, both holding "ABCD", but living at different memory addresses.
That's why:
s9.hashCode()ands11.hashCode()are the same:String'shashCode()is calculated based on the string's content. Since both have "ABCD", their hash values match perfectly.s9 == s11returnsfalse: 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
相关产品推荐
相关产品推荐

