How can we determine if two objects are equal in Java?

In Java, you can check if two objects are equal by using the following method:

  1. The book was too difficult for him to understand.
  2. The project is scheduled to be completed in two weeks.
Object obj1 = new Object();
Object obj2 = obj1;
boolean isEqual = (obj1 == obj2); // true
  1. is equivalent to
  2. is equal to
  3. is equivalent to
public class MyClass {
    private int value;

    public MyClass(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        MyClass other = (MyClass) obj;
        return value == other.value;
    }
}

MyClass obj1 = new MyClass(10);
MyClass obj2 = new MyClass(10);
boolean isEqual = obj1.equals(obj2); // true

Please note that if the equals() method is rewritten, the hashCode() method usually needs to be rewritten as well to ensure that when two objects are equal, their hash codes are also equal.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds