MyClass Object Instance

I need to make an equality function for MyClas.

public class MyClass { boolean equals(Object value) { if (... value is type of MyCLass ...) { return= ... check conditions...; } else return false; } } 

To do this, I need to know if the value of Object is a MyClass type. How to do it?

+4
source share
7 answers

To check if value type MyClass :

  if( value instanceof MyClass) 
+5
source
Operator

instanceof used to determine this. It is an infix, so use it like that ...

 (value instanceof MyClass) 
+1
source
  public class MyClass { boolean equals(Object value) { if (value instanceof MyCLass) { return= ... check conditions...; } else return false; } } 
+1
source

You can do

 @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MyClass myClass = (MyClass) o; //Your logic 

You can also use instanceof instead of the getClass() approach.

+1
source

Just a little IDE trick. Just to save some time.

In eclipse, you can do this by right-clicking on the class file and select the source ---> generate the hashCode () and equals () method, select the whole attribute that you need to compare, and the IDE will create the appropriate code for you

Excerpt

 public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Employee other = (Employee) obj; if (firstName == null) { if (other.firstName != null) return false; } else if (!firstName.equals(other.firstName)) return false; if (id != other.id) return false; if (lastName == null) { if (other.lastName != null) return false; } else if (!lastName.equals(other.lastName)) return false; if (salary != other.salary) return false; return true; } 
+1
source
 value instanceof ClassName 

the instanceof keyword is checked, where value is a subclass for ClassName if yes reutns true and otherwise returns false

0
source

Altitude RTTI (real-time authentication) is considered a code smell by some people, there are two alternatives: one should use the instanceof operator:

 if(value instanceof MyClass) 

On the other hand, you can use the full-fledged method from the Class Class , which defines two objects, you can determine whether they belong to the same hierarchy (much more powerful than instanceof IMO):

 if(value.getClass().isAsignableFrom(getClass())) 

This second approach determines whether the value is the same class or superclass / superinterface of the current class ( this ) at runtime specified by any kind of object. This isAsignableFrom stands out, since with instanceof you need to know the reference type at compile time.

0
source

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


All Articles