I am having a java class Rec. I have two instance of it Rec1 and Rec2. I want to check whether the values of Rec1 and Rec2 are equal. If i do Rec1.equals(Rec2) is it correct way of doing it?
class Rec {
private BigDecimal RecordId = null;
private BigDecimal recSubNum = null;
private BigDecimal FileId = null;
private String Category = null;
private BigDecimal status = null;
private BigDecimal errorCode = null;
}
You need to implement the
equals()
andhashCode()
methods to implement object equality in Java:Note: the equals/hashCode contract for Java means that for any two objects a and b:
and if two objects are equal then
a.hashCode()
must equalb.hashCode()
.Edit: there are two ways of checking if the types match. Either:
or
These two do different things and you should select the correct one depending on what you want to do. I generally prefer the first one unless you know you need the second. What's the difference?
Looks reasonable right? What if the class gets extended:
Still looks reasonable? It's broken.
That's why I favour
getClass()
overinstanceof
unless I really want subclass equality.if Rec is a user defined class then you really should override the equals method otherwise it will just call the equals method in the Object class;
something like :