Wednesday, 19 June 2024

Java equals() and hash() example

 

public class TrophyCalculationPayload {
private List<Integer> playerIds;
private Integer companyId;
private Integer gameId;
private String gameType;
private Integer point;
private Integer time;
private Integer highScore;
private Integer gameSessionId;
private String timeZone;
private Integer servedQuestionCount;
private Integer correctAnswerCount;

@Override
public boolean equals(Object other) {
if (this == other) {
System.out.println("first if");
return true;
}
if (other == null || getClass() != other.getClass()) {
System.out.println("second if");
return false;
}

TrophyCalculationPayload otherPayload = (TrophyCalculationPayload) other;

if( Objects.equals(companyId, otherPayload.companyId) &&
Objects.equals(gameId, otherPayload.gameId)) {
System.out.println("third if");
}
return true;
}

@Override
public int hashCode() {
return Objects.hash(companyId, gameId);
}
}
 
 public static void main(String[] args) {
TrophyCalculationPayload payload= new TrophyCalculationPayload(Arrays.asList(1,2,3),1,1,"game",1,1,1,1,"tz",1,1);
TrophyCalculationPayload payload1=new TrophyCalculationPayload(Arrays.asList(1,2,3),1,1,"game",1,1,1,1,"tz",1,1);
TrophyCalculationPayload payload3=payload1;
String name="pawan";
String name1="pawan";

String name2=new String("pawan");
String name3=new String("pawan");
System.out.println("--------"+ (name==name1));
System.out.println("--------"+ name.equals(name1));
System.out.println("--------"+name2.equals(name3));
System.out.println("--------"+name.equals(name1));
System.out.println("--------"+name1.equals(name));
//
System.out.println("--------"+payload.equals(payload1));
System.out.println("--------"+payload1.equals(payload3));
System.out.println("----payload----"+payload.hashCode());
System.out.println("----payload1----"+payload1.hashCode());
 
 Note In string class equals() method overided to compare compare content 
 But Object class equals() method overided to compare references.
 
 So when we compare 
 System.out.println("--------"+ name.equals(name1));
 
it retuns true;
but when compare User defined class then it return false,because  equals()
default overided behavior is to compare object references.


 


 
 
 
 
 

No comments:

Post a Comment