My Thinking In Java Reading Notes (2)

xiaoxiao2021-03-06  98

I will introduce some Java's basic processing mode for objects.

First look at an example of object equivalence (Object Equivalence):

First look at the following code:

PUBLIC CLASS Equaltest1 {

Public static void main (String [] args) {

Integer n1 = new integer (20);

Integer n2 = new integer (20);

System.out.println (n1 = = n2);

System.out.println (N1! = N2);

}

}

The purpose of the program is to output the comparison result in parentheses (Boolean value), and the person who first contact Java is easy to think that the output is first True and then FALSE.

But in fact, the result is first false and then True, because although the value of the two Integer objects is different, its REFERENCE is different. (Note: There have been introduced in my last study notes, and will not be described here.)

To explain the above problem, we should learn about Java's basic processing mode for objects:

When you operate an object, what you do is actually its reference, such as A = B, will point A and B to the object points to the original B, if you change A, then At the same time, change B content! Because A and B have the same Object Reference.

The REFERENCE stored in the original A is overwritten during assignment, and it is actually lost, because the garbage collector cleaned the object that the Reference originally directed at the appropriate time.

So how do you know if the content of the object is equal? Here is Equals (), please see the following code:

PUBLIC CLASS Equaltest2 {

Public static void main (String [] args) {

Integer n1 = new integer (20);

Integer n2 = new integer (20);

System.out.println (n1.equals (n2));

}

}

The output is the True that I expect in my door. Then, things will not be so simple, if there is a self-owned class, what is the matter? Please see the other code:

Class value {

INT I;

}

PUBLIC CLASS Equaltest3 {

Public static void main (String [] args) {

Value v1 = new value ();

Value v2 = new value ();

v1.i = v2.i = 20;

System.out.println (v1.equals (v2));

}

}

The result has output false, why? ?

In fact, the default behavior of equals () is to compare with Reference, so unless you are override equals (), you will not get expected results, and most of the Class of the Java Standard Library Cover Equals (), so they all compare whether the contents of the object are the same, so that the above problem is not difficult to solve.

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

New Post(0)