简体   繁体   中英

Question about Object Identity and Object Equality and String class exception

This is a Java and C# question. We all know that, Object Identity(==) tests whether two objects refer to the same location and Obejct Equality(Equals method) tests whether two different (non identical)objects have the same value .But In case of string object Object Identity and Object Equality are same. For eg Below two boolean expressions in if statements return true

string a="123";
string b="123";
if(a==b)
if(a.Equals(b))

Why is it so?? What is the rational behind this design decision?

Java and C# both use a memory-saving technique called string interning . Because strings are immutable in these languages, they can pool frequently-used strings (included hard-coded string literals, like in your example) and use multiple references to that one string in memory to save space.

As far as I know, in .net the == Operator for Strings is overloaded to use Equals() instead of object identity. See this explanation for details: http://www.dotnetperls.com/string-equals

For if you need to know if it's really the same object, use this:

Object.ReferenceEquals(string1, string2)

Actually, at least in Java, there is a caching mechanism on strings. A pitfall is that two strings that are equal will sometimes, but not always return true when applying the identity operator. the following code prints false:

String a="123";
String b="12";
b=b+"3";
System.out.println(a==b);

If you really want to make sure, that a.equals(b) == true but (a==b) == false evaluates to false for two String a and b, then you can use the completely undervalued (^^) String constructor:

String a = new String("abc");
String b = new String("abc");
if (a.equals(b)) {
   doTheyAreEqual();
   if (a != b) {
     doButNotTheSame();
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM