Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing .equals(Die aDie) method and static variables

Tags:

java

I am creating the method .equals(Die aDie) in my program. Do I compare every instance variable including static ones?

like image 606
malhobayyeb Avatar asked Feb 25 '26 11:02

malhobayyeb


1 Answers

boolean equals(Die aDie)

is wrong, classes will call the equals(Object) method and ignore your equals(Die). Also implement the int hashCode() method using the same fields that equals(Object) uses.

 @Override public boolean equals(Object aDie){
     if(aDie == null || aDie.getClass() != Die.class)return false;
     if(aDie == this)return true;
     Die other = (Die)aDie;
     ...   
 }
 @Override public int hashCode(){
     ...
 }

You can ignore static fields since they are the same for every Die.

like image 50
josefx Avatar answered Feb 27 '26 01:02

josefx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!