== with Equals ()

xiaoxiao2021-03-06  15

Write a program first

Public class equivalence {

Public static void main (String [] args) {

Integer n1 = new integer (47);

Integer n2 = new integer (47);

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

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

}

}

The result of the output of this example we expected should be first True and then False because the values ​​of the two Integer objects are the same. However, although the content of the two objects is the same, its References is different, because == and! = The operator is compared to Object References, so the actual output result is FALSE and then TRUE.

If I want to know if the content of the object is equal, we have to use equals (). Any object (which does not contain the basic models that can be used normally == and! =) Have this function. The following is a way of use

Public class equivalence {

Public static void main (String [] args) {

Integer n1 = new integer (47);

Integer n2 = new integer (47);

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

}

As a result, if you expect, it is true. However, things are not so simple. such as

Class value {

INT I;

}

Public class equalsmethod {

Public static void main (String [] args) {

Value v1 = new value ();

Value v2 = new value ();

v1.i = v2.i = 100;

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

}

}

The situation is returned to the origin: The output result is false. This is because the default behavior of equals () is compared to References. So unless you override Equals () in your class, you can't get the behavior you want.

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

New Post(0)