Easy-to-misclassics summary --- (Equals vs ==)

xiaoxiao2021-03-06  171

== and Equals "Test the item reference, only when two reference points to the same object, == The result of the operator is True, the same, only when two reference points to different objects,! = Operator The result is TRUE. The processing of these two operators is independent of the content of the object. It is necessary to pay special attention to the use of == in String, because Java saves memory, will maintain unique String objects in a round of regions. So if you use the same string in the category, Java will only create a unique string. "[Reference -> (Equals and ==)] Equals and == are default compared to whether two Reference is in Object. It is point to the same object, but since Equals is overwritten in String, Equals is comparable to String. But what is the comparison of the content of the object of other classes, then as long as you have overwritten, take a study: class becauselove {public string str = ""; becauselove (string s) {str = s;} // ------- Override ------------- Public Boolean Equals (Object O) {if (this == O) {// Compare if it is pointing The same object return true;} The effect of if (o instanceof becauselove) {// instanceOf operator is to determine if a variable is an object BecauseLOVE BL = (BecauseLOVE) O at the class pointed out by the right operand. Return Str.Equals (BL. Str);} Return False;} // -------------------------------- } Class testbl {becauselove BL1 = New BecauSelove ("first"); BecauseLove Bl2 = New BecauSelove ("first"); Void Compare (BecauseLOVE A, BECAUSELOVE B) {if (a.equals (b)) {system.out.println ("YES" }}} Void test () {Compare (BL1, BL2);} public static void main (string args []) {testbl t = new testbl (); t.test ();}} --- ---------------------------------- This can compare the content of the object. Of course, pay attention to some problems during the overwriting process, what is the problem is still studying ...

转载请注明原文地址:https://www.9cbs.com/read-128072.html

New Post(0)