Comparing Java Objects

I am new to Java and reading a Java book; at some point it talks about when you want to override the built-in function, equals (). For example, if an object has a variable identifier, and two objects have the same identifier, you can consider them equal. He gave an example code that looks something like this:

public boolean equals(Object obj) {
    if((obj != null) && (obj instanceof myClass)) {
        myClass object1 = (myClass)obj;
        if(this.ID == object1.ID) {
            return true;
        }
    }
    return false;
}

I do not quite understand what is happening on the third line. I'm not sure why this is necessary, and you cannot just compare obj.ID and this.ID in the if () statement. I assume this is because obj is simply declared as a generic object that may not have an ID, so you need to create a new object1 object that has the correct class to look at the ID.

Will I fix it here? What exactly is happening on this line?

+4
6

: obj Object Object , a String, , ID, , , . , , , , obj ( , , ), ( , ) ,

, , myClass. . myClass object1 = (myClass)obj; , , object1 , obj, , , myClass.

0

Object obj . , .

myClass object1 = (myClass) obj;

, , , ClassCastException.

, .

: obj != null , null instanceof . .

Object o = null;
boolean b = o instanceof Object; // always false, never throws an exception.

.

public boolean equals(Object obj) {
    if(obj instanceof myClass) {
        myClass object1 = (myClass)obj;
        return ID == object1.ID;
    }
    return false;
}

public boolean equals(Object obj) {
    return obj instanceof myClass && ID == ((myClass) obj).ID;
}

Java 8

public boolean equals(Object obj) {
    return Optional.ofNullable(obj)
                   .filter(o - > o instanceof myClass)
                   .map(o -> (myClass) o)
                   .filter(m -> ID == m.ID)
                   .isPresent();
}
+4

.

, java, , , int, char, double , , .

, Object obj Object, .

, , myClass object1, ; object1, myClass. .

, myClass object1 = (myClass)obj;, obj object1. , cast ( (myClass)), , , , , obj myClass . , .

obj object1 , object1 , myClass, .

+1

. if, obj instanceof myClass. , myClass. , myClass , , , ID, .

0

" ".

obj instanceof myClass , obj , this. , Object obj myClass object1

0

null , instanceof - false null s.

:

if (obj instanceof myClass) {

, ID (, String).

0

Source: https://habr.com/ru/post/1619585/


All Articles