I tested my code:
Set<Solution> s = new HashSet<>();
Date d = new Date();
Solution a = new Solution();
Solution sol = new Solution(3, "ala", 2.2, d, a);
System.out.println(s.add(sol));
System.out.println(s.add(sol));
output is:
true
false
package com.codegym.task.task21.task2106;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
/*
Bug in equals/hashCode
*/
public class Solution {
private int anInt;
private String string;
private double aDouble;
private Date date;
private Solution solution;
public Solution() {
}
public Solution(int anInt, String string, double aDouble, Date date, Solution solution) {
this.anInt = anInt;
this.string = string;
this.aDouble = aDouble;
this.date = date;
this.solution = solution;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o instanceof Solution) {
return false;
}
if (o == null) {
return false;
}
Solution solution1 = (Solution) o;
return Objects.equals(this.anInt, solution1.anInt) && Objects.equals(this.string, solution1.string) &&
Objects.equals(this.aDouble, solution1.aDouble) && Objects.equals(this.date, solution1.date) &&
Objects.equals(this.solution, solution1.solution);
}
@Override
public int hashCode() {
int result;
long temp;
result = anInt;
temp = aDouble != +0.0d ? Double.doubleToLongBits(aDouble) : 0L;
result = 31 * result + (int) (temp ^ (temp >>> 32));
result = 31 * result + (solution != null ? solution.hashCode() : 0);
return result;
}
public static void main(String[] args) {
}
}