Equals () and operator "==" in java

I know that equals() will compare the value of objects, the '==' operator checks if the variable points to the same memory.

I do not understand how equals() compare the value of objects, for example:

 class Test { public Test(int x, float y) { this.x = x; this.y = y; } int x, float y; } Test test1 = new Test(1,2.0); Test test2 = new Test(1,2.0); 

So, if I use equals() , will it compare all properties in each object?

What about what we're talking about String? using equals () and operator "==", do we still need to override equals ()?

+8
java equals
source share
3 answers

No, if you do not override the equals method in your class, then equals matches == . See the documentation for this:

The equals method for the Object class implements the most discriminatory possible equivalence relation on objects; that is, for any nonempty reference values ​​x and y, this method returns true if and only if x and y refer to the same object (x == y is true).

The documentation also indicates what requirements exist for equals methods if you want to implement it.

+20
source share

Not unless you overload it properly in accordance with the rules laid down by Joshua Bloch .

The default behavior checks link equality using == .

It is important to override equals and hashCode for your objects, especially if you intend to use them in java.util.Collections.

+11
source share

The equals method is defined in the Object class, and since all objects in Java are implicitly or explicitly inherited from this class, they also inherit the equals () method implemented by Object. By default, the implementation of Object will simply return true if the objects pass the condition "==".

However, you can override the equals () method in your own class and specify criteria that need to be checked to ensure that the two objects are significantly equal. For example, you can say that two instances are equal only if each of its attributes contains the same values ​​as the other object, or instead you can simply check the multiple attributes that make up the business key objects and ignore rest.

Equality of String classes follows the same rules as any other class in Java; "==" will be true if they refer to the same instance, and equals () will be true if they contain the same value.

0
source share

All Articles